Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed join lines together

Tags:

regex

linux

sed

what would be the sed (or other tool) command to join lines together in a file that do not end w/ the character '0'?

I'll have lines like this

412|n|Leader Building Material||||||||||d|d|20||0 

which need to be left alone, and then I'll have lines like this for example (which is 3 lines, but only one ends w/ 0)

107|n|Knot Tying Tools|||||Knot Tying Tools  |||||d|d|0||0 

which need to be joined/combined into one line

107|n|Knot Tying Tools|||||Knot Tying Tools|||||d|d|0||0 
like image 956
veilig Avatar asked Oct 21 '11 16:10

veilig


People also ask

How do you join two lines in sed?

sed operates by performing the following cycle on each lines of input: first, sed reads one line from the input stream, removes any trailing newline, and places it in the pattern space. Then commands are executed; […]. Add a newline to the pattern space, then append the next line of input to the pattern space.

Can sed match multiple lines?

By using N and D commands, sed can apply regular expressions on multiple lines (that is, multiple lines are stored in the pattern space, and the regular expression works on it): $ cat two-cities-dup2.


1 Answers

 sed ':a;/0$/{N;s/\n//;ba}' 

In a loop (branch ba to label :a), if the current line ends in 0 (/0$/) append next line (N) and remove inner newline (s/\n//).

awk:

awk '{while(/0$/) { getline a; $0=$0 a; sub(/\n/,_) }; print}' 

Perl:

perl -pe '$_.=<>,s/\n// while /0$/' 

bash:

while read line; do      if [ ${line: -1:1} != "0" ] ; then          echo $line     else echo -n $line fi done  
like image 109
ninjalj Avatar answered Oct 24 '22 19:10

ninjalj