Shell script Sed read one file and write to another only on the first occurrence of a string

Asked

Viewed 1,858 times

1

Good afternoon,

I am trying to read from an X file and write to a Y file when a specific String appears. But I only want to include it once. Example I’m trying to make:

sed -i '/, pasta/r teste.txt' Report.html

This command is reading all the strings ", folder" and is including below the contents of the test.txt file. But I want to make it include only the first occurrence of the string ", folder" . A command like:

sed -i '0,/, pasta/r teste.txt' Report.html

The above syntax is wrong, as it would be correct to include the contents of the file only in the first occurrence of the string ", folder" ?

2 answers

1

If it’s just to find an occurrence, without substitutions or many conditions for this match to be true, I would use the grep.

grep -o -a -m 1  -h  "pasta" teste.txt > report.html

Parameters:

-o = Shows only the searched word, if you remove this, shows the whole match line.

-a = Processes the file as text.

-m 1 = Stop searching after the first true match

-h = Does not show the name of the file where match was found.

  • but I would like to make the substitution, I got with the command: sed -i $(awk '/, past/{print NR;exit}' Report.html)'r test.txt' Report.html

  • It seems to me that you are not solving the request.

0

perl -p0e  's/(, pasta)/"$1\n" . `cat teste.txt`/e ' Report.html

i.e.: replaces the first occurrence of ", pasta" by the result of

eval("$1\n" . `cat teste.txt`)

(perl -0 ... file loads the whole file; s/ / / makes only one substitution)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.