Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting line between two lines having second line starting with certain pattern

I want to insert a line between two lines, only if the second line matches a certain pattern

for example the input file is as follows:

pattern (match 1, line 1)
line 2
line 3
line 4
line 5 (before pattern)
pattern (match 2, line 5)
line 7
line 8
line 9
line 10 (before pattern)
pattern (match 3, line 11)
line 12

I want to insert lineToInsert between line 5 and pattern and between line 10 and pattern

I have tried this command:

sed 'N;s/\n\(pattern\)/\n\ 
lineToInsert\n\1/'

I expect this to work, but it only works if the matched pattern exists on an even line only !!

So, How could I achieve this using sed or any other tool / command? and Why the previous command does not work ?

like image 511
Devos Avatar asked Dec 26 '22 20:12

Devos


2 Answers

sed has an insert command:

sed '1n; /^pattern/i line to insert'
like image 113
glenn jackman Avatar answered Jan 26 '23 00:01

glenn jackman


With awk you could do something like this:

awk 'NR>1&&/pattern/{print "lineToInsert"}1' file
like image 43
user000001 Avatar answered Jan 25 '23 23:01

user000001