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?
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.
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.
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.
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).
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
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