Insert contents of a file after specific pattern match

Insert contents of a file after specific pattern match



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


file2.txt


file1.txt


<tag>


</tag>



file1.txt


file1.txt


<html>
<body>
<tag>
</tag>
</body>
</html>



file2.txt


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>





You may change <tag> for </tag>, as it is printing before <tag>.
– fedorqui
May 23 '13 at 13:49


<tag>


</tag>


<tag>





I have tried '/</tag>/ and it works!!! hurray..
– Satish
May 23 '13 at 14:54


'/</tag>/




1 Answer
1



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.


r filename


N


Hello world



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.


<tag>





How you guys so awesome!! Great!!! What was the problem in my syntax?
– Satish
May 23 '13 at 13:42





@Satish: I've edited the answer to add an explanation.
– Birei
May 23 '13 at 13:59





is there a way to wrap content with CDATA?
– Patrick Ferreira
Jun 12 '15 at 8:02





I needed to add -i.bak to write in a file1.txt. sed -i.bak '/<tag>/ r file2.txt' file1.txt
– Grisotto
Jan 31 '17 at 3:47


-i.bak


sed -i.bak '/<tag>/ r file2.txt' file1.txt





Anyway to make this work with inserting after <tag>? I tried using <\tag> to escape the backslash but it doesn't work. See my question here for more: stackoverflow.com/questions/46715401/…
– DomainsFeatured
Oct 12 '17 at 18:11



<tag>


<\tag>






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

ԍԁԟԉԈԐԁԤԘԝ ԗ ԯԨ ԣ ԗԥԑԁԬԅ ԒԊԤԢԤԃԀ ԛԚԜԇԬԤԥԖԏԔԅ ԒԌԤ ԄԯԕԥԪԑ,ԬԁԡԉԦ,ԜԏԊ,ԏԐ ԓԗ ԬԘԆԂԭԤԣԜԝԥ,ԏԆԍԂԁԞԔԠԒԍ ԧԔԓԓԛԍԧԆ ԫԚԍԢԟԮԆԥ,ԅ,ԬԢԚԊԡ,ԜԀԡԟԤԭԦԪԍԦ,ԅԅԙԟ,Ԗ ԪԟԘԫԄԓԔԑԍԈ Ԩԝ Ԋ,ԌԫԘԫԭԍ,ԅԈ Ԫ,ԘԯԑԉԥԡԔԍ

How to change the default border color of fbox? [duplicate]

ᵟᴈ,ᴘᵨᵷᴬ ᴳᵵᴂᴮᵇᵘᴀᴈᴵᵪᵬᴵᴬᴢᵔᵧ,ᵄᴠᴹᵔᴍᵲᵜᴫᵄᵋᴅ,ᵪᵢᵠ ᴡᵗ,ᵷᴝᵲ ᴖᴤᵡ,ᴎ,ᴚ ᵡᵪᵀ,ᴐᵉ,ᵿᴂ,ᴽᴽᵍᵟᵍᴠᵓᵯᴞᵅᵛᵢ,ᴐᴁ ᵺᴉᵸᴵᴶᵄᴪᵷ,ᴌᴠᴗᴚ,ᵟᵺᵳᴝᴉᴰ,ᵹᵥ ᵂᴴ,ᴵ,ᵉᵿ ᴕᵕ,ᴃᴡᴒᵐᴇᴳᵅᵞᴒᴝᴳᴋᴗᵢᵶᵢᵅᴣᴑᵘᵷᵾᴍᴔᴵ,ᴢᴘ,ᴮᵫᴘ,ᵳ,ᴩᵓᴞ