Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using sed, Insert a line above or below the pattern? [duplicate]

Tags:

scripting

sed

awk

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 
like image 241
vehomzzz Avatar asked Jul 27 '12 20:07

vehomzzz


People also ask

How do you insert a sed line after a pattern?

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.

How do you add a line at the end of a file in Linux using sed?

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.


1 Answers

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 
like image 96
Kamal Avatar answered Sep 19 '22 09:09

Kamal