开发者

remove newline between two string with sed command in unix shellscript

I have a file (test.dat) which contains data like this

459|199811047|a |b |shan
kar|ooty|
460|199811047|a |b |guru|cbe|

but I need it like:

459|199811047|a |b |shankar|ooty|
460|199811047|a |b |guru|cbe|

While reading the data from this file, I don't want to remove newline from the end of each record. I just want to remove the \n between two string (like:shankar) inside the pipe symbol.

actually inside the unix my dat file... consist of 500 character.. so the first 300 character appear in the first line and got break(newline)for the next 200 character... but the 500 should be treated like single line.. so am tryin开发者_StackOverflowg to append the characters which has got break because of newline.


Inspired by How can I replace a newline (\n) using sed?

sed ':a;N;/|$/!ba;s/\n//g'

Explanation(for the difference from the inspiration):

  1. If we encounter a line does not end with '|', branch to the created register/|$/!ba


It isn't clear really what the criteria for joining two lines are. However, this will probably do the trick on the data shown:

sed -e '/|shan$/N;s/|shan\nkar|/|shankar|/' test.dat

Tested with sed on MacOS X 10.6.6.

If the criterion is 'if the line does not end with a pipe, join it with the next line', then this works:

sed -e '/[^|]$/{N;s/\n//;}' test.dat

The search says 'if the line does not end with a pipe'; '{' starts a group of operations; N concatenates the next line with a newline in between; the s/\n// deletes the newline; '}' ends the group of operations.


awk 'ORS=/^[0-9]/?"\0":"\n"' file

ruby -ne 'print /^\d+/?"#{$_.chomp}":"#{$_}";' file


A slightly different approach:

sed '/^.\{300\}$/{N;s/\n//}' inputfile

If a line consists of exactly 300 characters, append the next line.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜