Insert text into file after a specific text

2019-04-13 13:27发布

问题:

I would like to insert an output into a file...in the next line after a specific text.

In my output (Text1.txt) I have different lines with domain names:

hxxp://example1.com
hxxp://example2.com

I would like to insert this lines into another text file (Text2.txt) after the line with the text "URLs found" (Note: I don't know the line number).

bla
bla
bla
URLs found
hxxp://example1.com
hxxp://example2.com
bla
bla

How can I do this?

回答1:

You could do this using sed:

sed -i '/URLs found/r Text1.txt' Text2.txt

When the pattern is matched, insert the contents of Text1.txt. The -i switch means that sed edits the file in-place.

Alternatively, you could do the same thing in awk:

awk 'NR==FNR{a[n++]=$0;next} 1; /URLs found/{for (i=0;i<n;++i) print a[i]}' Text1.txt Text2.txt > tmp && mv tmp Text2.txt

Read all of the lines in Text1.txt into an array. the 1; means that every line in Text2.txt is printed. When the pattern is matched, the contents of the array are also printed.



回答2:

sed makes it really easy:

sed -i '/URLs found/ r Text1.txt' Text2.txt


标签: bash shell