3

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?

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
user3022917
  • 579
  • 2
  • 8
  • 20

2 Answers2

5

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.

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
  • How would you use this with a variable instead of a file (Text1.txt)? – Flimtix Feb 04 '22 at 16:04
  • Just found it: `sed -i "/$var1/a $var2" Text2.txt` – Flimtix Feb 04 '22 at 16:34
  • 1
    @Nanoserver, yes, you can use double quotes around your sed command string and then the shell will expand those variables. Just be careful, because any characters that are significant as part of a regular expression (e.g. `.` or `&`) will be interpreted by sed. See [this answer](https://stackoverflow.com/q/29613304/2088135) for more info on what you would need to do to reliably work with variables with arbitrary values. – Tom Fenech Feb 08 '22 at 12:34
3

sed makes it really easy:

sed -i '/URLs found/ r Text1.txt' Text2.txt
Tim Zimmermann
  • 6,132
  • 3
  • 30
  • 36