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 ?
sed
has an insert command:
sed '1n; /^pattern/i line to insert'
With awk you could do something like this:
awk 'NR>1&&/pattern/{print "lineToInsert"}1' file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With