Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert multiple lines into a file after specified pattern using shell script

I want to insert multiple lines into a file using shell script. Let us consider my input file contents are: input.txt:

abcd accd cdef line web 

Now I have to insert four lines after the line 'cdef' in the input.txt file. After inserting my file should change like this:

abcd accd cdef line1 line2 line3 line4 line web 

The above insertion I should do using the shell script. Can any one help me?

like image 695
user27 Avatar asked Mar 19 '14 05:03

user27


People also ask

How do I write multiple lines in a shell file?

To add multiple lines to a file with echo, use the -e option and separate each line with \n. When you use the -e option, it tells echo to evaluate backslash characters such as \n for new line. If you cat the file, you will realize that each entry is added on a new line immediately after the existing content.

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 lines in shell?

Using '>>' with 'echo' command appends a line to a file. Another way is to use 'echo,' pipe(|), and 'tee' commands to add content to a file.

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

Use $ a . It's useful to know how to actually do this with sed. Sometimes you want to use sed to make multiple changes to a file, including adding a line to the end, and it's nice to be able to do that in a single command. This does not work for an empty file (0 bytes) created by touch (like asked).


1 Answers

Another sed,

sed '/cdef/r add.txt' input.txt 

input.txt:

abcd accd cdef line web 

add.txt:

line1 line2 line3 line4 

Test:

sat:~# sed '/cdef/r add.txt' input.txt abcd accd cdef line1 line2 line3 line4 line web 

If you want to apply the changes in input.txt file. Then, use -i with sed.

sed -i '/cdef/r add.txt' input.txt 

If you want to use a regex as an expression you have to use the -E tag with sed.

sed -E '/RegexPattern/r add.txt' input.txt 
like image 144
sat Avatar answered Sep 29 '22 01:09

sat