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
The sed command can add a new line after a pattern match is found. The "a" command to sed tells it to add a new line after a match is found. The sed command can add a new line before a pattern match is found. The "i" command to sed tells it to add a new line before a match is found.
The following “sed” command shows how to change the content of the file permanently. The “i” option is used with the “sed” command to insert a new line in the file based on the pattern.
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
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