Rakiz
Rakiz

Reputation: 25

Shell script Sed - How to read a file and write in another file only in the first occurrence of a string?

I am trying to read the content of the file test.txt and write in another file Report.html, only in the first match of a string. Something like:

sed -i '/, past/r test.txt' Report.html

This command above is reading all strings ", past" and including the content of the test.txt in all strings ", past". But I just want that includes in the first occurrence of the string ", past". A command like:

sed -i '0,/, past/r test.txt' Report.html

The command above is not working, what's the correct syntax for that?

Upvotes: 0

Views: 936

Answers (1)

Jeff Y
Jeff Y

Reputation: 2456

As the sed r command does not take range, and sed control does not otherwise allow "first only", I think you need to "calculate" the line number of interest and feed that to sed:

sed -i $(awk '/, past/{print NR;exit}' Report.html)'r test.txt' Report.html

Only do this if you're guaranteed that , past occurs in Report.html somewhere. If not, store the $(awk...) result in a variable and check it first. Otherwise the sed will do the include for every line.

Upvotes: 1

Related Questions