Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert 4 newlines before pattern match with SED?

How to enter 4 blanklines before pattern matches?

I can do

sed '/patterntosearch4/G' 1.txt > 2.txt 

to create a new file (2.txt) with a blank line AFTER each pattern.

But how to enter 4 blank lines BEFORE match?

Manpage SED didnt seem to provide any answers.

Any help is much appreciated!!

like image 950
Michel Kapelle Avatar asked Feb 18 '14 15:02

Michel Kapelle


2 Answers

This might work for you (GNU sed):

sed '/patterntosearch4/i\\n\n\n' file

or if you prefer:

sed -e '/patterntosearch4/!b' -e 'G' -e 's/\(.*\)\(.\)/\2\2\2\2\1/' file

BTW as you use the G command, which inserts a newline following the line with the pattern match, I guessed you wanted a newline inserted before the line with the pattern match.

like image 85
potong Avatar answered Oct 04 '22 19:10

potong


In the famous sed one-line blog (http://www.catonmat.net/blog/wp-content/uploads/2008/09/sed1line.txt)

# insert a blank line above every line which matches "regex"
 sed '/regex/{x;p;x;}'

so in your case,

sed '/atterntosearch4/{x;p;p;p;p;x}' file

or

sed '/atterntosearch4/{x;P;P;P;P;x}' file
like image 40
BMW Avatar answered Oct 04 '22 19:10

BMW