0

I'm trying to use code that I found here: Insert contents of a file after specific pattern match

However, when I add a backslash to the code, it doesn't work. So, then, I followed the instructions here: Slash and backslash in sed to change the delimiters in sed. However, when I do that, the insert (which should be a few lines), turns into thousands.

Here's my attempt:

sed ':<\tag>: r file1.txt' file2.txt

Example:

File1.txt

Hello World 1
Hello World 2

File2.txt:

<thanks>
<tag>
<example>
<new>
<\new>
<\example>
<\tag>
<\thanks>

Desired output:

<thanks>
<tag>
<example>
<new>
<\new>
<\example>
<\tag>
Hello World 1
Hello World 2
<\thanks>

If you could please help me insert the file contents after a line match while escaping a backslash, I would really appreciate it.

DomainsFeatured
  • 1,426
  • 1
  • 21
  • 39

3 Answers3

2

try this

sed '/<\\tag>/r file2' file1

I think you swapped file1 and file2.

karakfa
  • 66,216
  • 7
  • 41
  • 56
1

Try with following awk too once.

awk '/<\\tag>/{print;system("cat File2.txt");next} 1' File.txt

To save output into File.txt itself following may help you in same.

awk '/<\\tag>/{print;system("cat File2.txt");next} 1' File.txt > temp_file && mv temp_file  File.text
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
1

Same answer as your other question (see https://stackoverflow.com/a/46720002/1745001), just print the new record after instead of before the target line:

awk 'FNR==NR{n=n ORS $0; next} /<\\tag>/{$0=$0 n} 1' file1 file2

I highly recommend the book Effective Awk Programming, 4th Edition, by Arnold Robbins.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185