Add text from inside of a file above a line match in another file

Viewed 40

I have a file File1.txt that contains the following:

abc
def
ghi

I have another file File2.txt that contains the following:

123
456
789

I would like to add the contents of file 1 above 789 to give:

123
456
abc
def
ghi
789

Ultimately using sed or awk. I tried a workaround where I used:

file1="$(cat File1.txt)"
sed -i "/^789/i $file1 " File2.txt

However this does not work as intended. Any help would be much appreciated, thank you for your expertise.

2 Answers

Execute cat with GNU sed:

sed '/^789$/e cat file1' file2

Output:

123
456
abc
def
ghi
789

With any awk in any shell on every UNIX box for any value of 789:

$ awk 'NR==FNR{new=new $0 ORS; next} $0=="789"{printf "%s", new} 1' file1 file2
123
456
abc
def
ghi
789

The only caveat is that file1 can't be so massive that it doesn't fit in memory.

Related