Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert contents of a file after specific pattern match

Tags:

regex

linux

sed

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> 
like image 700
Satish Avatar asked May 23 '13 13:05

Satish


People also ask

How do I put text after a certain string in a file?

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.

How do you insert a sed line after a pattern?

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.

How do I add a value to a file in Linux?

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.


1 Answers

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.

like image 178
Birei Avatar answered Sep 26 '22 05:09

Birei