How to insert the content of a file into another file before a pattern (marker)?

sed has a function for that, and can do the modification in-place:

sed -i -e '/Pointer/r file1' file2

But this puts your Pointer line above the file1. To put it below, delay line output:

sed -n -i -e '/Pointer/r file1' -e 1x -e '2,${x;p}' -e '${x;p}' file2 

With `GNU sed`
sed '/Pointer/e cat file1' file2

As per manual for e [command]

Note that, unlike the r command, the output of the command will be printed immediately; the r command instead delays the output to the end of the current cycle.


Without using sed or awk.

First, find the line on which your pattern is:

line=$(grep -n 'Pointer' file2 | cut -d ":" -f 1)

Then, use 3 commands to output the wanted result:

{ head -n $(($line-1)) file2; cat file1; tail -n +$line file2; } > new_file

This has the drawback of accessing 3 times file2, but might be clearer than a sed of awk solution.


awk makes this fairly easy.
Insert the line before the file:

awk '/Pointer/{while(getline line<"innerfile"){print line}} //' outerfile >tmp
mv tmp outerfile

To make the inner file print after the Pointer line, just switch the order of the patterns (you need to add a semicolon to get the default action), and you can drop the line variable:

awk '//; /Pointer/{while(getline<"innerfile"){print}}' outerfile >tmp
mv tmp outerfile

And just because no one has used perl yet,

# insert file before line
perl -e 'while(<>){if($_=~/Pointer/){system("cat innerfile")};print}' outerfile

# after line
perl -e 'while(<>){print;if($_=~/Pointer/){system("cat innerfile")}}' outerfile