I need to edit a good number of files, by inserting a line or multiple lines either right below a unique pattern or above it. Please advise on how to do that using sed
, awk
, perl
(or anything else) in a shell. Thanks! Example:
some text
lorem ipsum dolor sit amet
more text
I want to insert consectetur adipiscing elit
after lorem ipsum dolor sit amet
, so the output file will look like:
some text
lorem ipsum dolor sit amet
consectetur adipiscing elit
more text
To append after the pattern: (-i is for in place replace). line1 and line2 are the lines you want to append(or prepend)
sed -i '/pattern/a \
line1 \
line2' inputfile
Output:
#cat inputfile
pattern
line1 line2
To prepend the lines before:
sed -i '/pattern/i \
line1 \
line2' inputfile
Output:
#cat inputfile
line1 line2
pattern