Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert text into file after a specific text

Tags:

bash

shell

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?

like image 805
user3022917 Avatar asked Oct 23 '25 08:10

user3022917


1 Answers

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.

like image 53
Tom Fenech Avatar answered Oct 25 '25 02:10

Tom Fenech



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!