Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

move line which matches pattern to previous line

Tags:

bash

sed

awk

I have a file with structure

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

and i want to move line which matches pattern "desc:" to previous line or delete '\n' in line which goes before every pattern "desc:".

desired output:

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

I've tried

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

with no result.

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

like image 444
Igor Voltaic Avatar asked Jun 10 '13 10:06

Igor Voltaic


People also ask

What is sed option?

sed is a stream editor. A stream editor is used to perform basic text transformations on an input stream (a file or input from a pipeline). While in some ways similar to an editor which permits scripted edits (such as ed ), sed works by making only one pass over the input(s), and is consequently more efficient.

How to remove lines using sed?

To Remove the lines from the source file itself, use the -i option with sed command. If you dont wish to delete the lines from the original source file you can redirect the output of the sed command to another file.

How do you go to the next line in a bash script?

Printing Newline in Bash Using the backslash character for newline “\n” is the conventional way. However, it's also possible to denote newlines using the “$” sign.


3 Answers

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...
like image 117
bartimar Avatar answered Nov 09 '22 16:11

bartimar


One way with 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:/ match lines that don't start with desc: not including the first line in the file NR>1.
  • {print OFS} print an output field separator before the matched line. In awk the default OFS is \n.
  • {printf "%s ",$0} print every line without a trailing newline.
  • END{print OFS} after the file has been read add a trailing newline.

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

like image 13
Chris Seymour Avatar answered Nov 09 '22 16:11

Chris Seymour


$ 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...
like image 4
Ed Morton Avatar answered Nov 09 '22 15:11

Ed Morton