I want to insert file content at specific pattern match. The following is an example: add file2.txt
content in file1.txt
between <tag>
and </tag>
.
file1.txt
<html> <body> <tag> </tag> </body> </html>
file2.txt
Hello world!!
I have tried following and it didn't work.
# sed "/\<tag\>/ { h r file2.txt g N }" file1.txt <html> <body> Hello World!! <tag> </tag> </body> </html>
A new line can be inserted after any string value using the “sed” command if the pattern defined in the command matches with any part of the string value. The following example shows how a new line can be added after a string value if a particular string exists anywhere in the string value.
There are different ways to insert a new line in a file using sed, such as using the “a” command, the “i” command, or the substitution command, “s“. sed's “a” command and “i” command are pretty similar.
You can use the cat command to append data or text to a file. The cat command can also append binary data. The main purpose of the cat command is to display data on screen (stdout) or concatenate files under Linux or Unix like operating systems.
Try following command:
sed '/<tag>/ r file2.txt' file1.txt
It yields:
<html> <body> <tag> Hello world </tag> </body> </html>
EDIT for explanation why your command doesn't work as you want: The r filename
command adds its content at the end of the current cycle or when next input line is read. And you are using the N
command which doesn't print anything but reads next line, so at that time Hello world
is printed and after that the normal stream of lines.
In my case, it reads line with <tag>
, then ends cycle, so prints the line and after it the content of the file and carry on reading until the end.
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