Move line matching pattern to previous line

I have a file with a structure

12312 desc: bleh... 9938 desc: blah... desc: bloh... desc: blih... desc: bluh... 9912 desc: blah... 

and I want to move the line that matches the "desc:" pattern in the previous line or delete the "\ n" in the line that goes before each "desc:" pattern.

desired result:

 12312 desc: bleh... 9938 desc: blah... desc: bloh... desc: blih... desc: bluh... 9912 desc: blah... 

I tried

 awk '!/desc:/{ printf "%s ",$0 getline printf "%s \n",$0 } /desc/{print}' file 

without result.

in fact, all the data is the output of awk -F\" '{print $4 "\t" $6}' maybe I can do something first?

+4
source share
5 answers

One way: awk :

 $ awk '!/^desc:/&&NR>1{print OFS}{printf "%s ",$0}END{print OFS}' file 12312 desc: bleh... 9938 desc: blah... desc: bloh... desc: blih... desc: bluh... 9912 desc: blah... 

Explanation:

  • !/^desc:/ matches lines that do not begin with desc: not including the first line in the file NR>1 .
  • {print OFS} print the output field delimiter before the matching line. In awk , the default value of OFS is \n .
  • {printf "%s ",$0} print each line without a trailing newline.
  • END{print OFS} after the file has been read, add the ending new line.

Live demo: http://ideone.com/ajH14u

+12
source

sed oneliner

 sed ':a $!N;s/\ndesc/ desc/;ta P;D' 

Will output

 12312 desc: bleh... 9938 desc: blah... desc: bloh... desc: blih... desc: bluh... 9912 desc: blah... 
+11
source
 $ cat file 12312 desc: bleh... 9938 desc: blah... desc: bloh... desc: blih... desc: bluh... 9912 desc: blah... $ awk '{printf "%s%s",(/^desc:/?OFS:ors),$0; ors=ORS} END{print ""}' file 12312 desc: bleh... 9938 desc: blah... desc: bloh... desc: blih... desc: bluh... 9912 desc: blah... 
+4
source

Perl Solution:

 perl -pe 's/\n/ /; ! /^desc:/ and print "\n" unless 1 == $.' FILE 
+3
source

Using

The contents of script.vim :

 set backup g/\v^desc/ normal kJ saveas! output.txt q! 

Run it like this:

 vim -u NONE -N -S script.vim infile 

And it will create an output.txt file with content:

 12312 desc: bleh... 9938 desc: blah... desc: bloh... desc: blih... desc: bluh... 9912 desc: blah... 
+1
source

Source: https://habr.com/ru/post/1485401/


All Articles