using sed to insert file content into a file BEFORE a pattern

Just use awk:

Print Bfile before the matched line:

awk 'NR==FNR{bfile = bfile $0 RS; next} /blah Blah/{printf "%s", bfile} {print}' Bfile Afile

print Bfile after:

awk 'NR==FNR{bfile = bfile $0 RS; next} {print} /blah Blah/{printf "%s", bfile}' Bfile Afile

Content of AFile

one
two
three
blah Blah
four

Content of BFile

...b...

Run these commands

# get line number
$ sed -n '/blah Blah/=' AFile
4

# read file just before that line
$ sed '3r BFile' AFile
one
two
three
...b...
blah Blah
four

This might work for you (GNU sed):

sed $'/blah Blah/{e cat BFile\n}' AFile

or:

sed -e 'N;/\n.*blah Blah/{r BFile' -e '};P;D' AFile

or as Alek pointed out:

sed '/blah Blah/e cat BFile' AFile

sed's r command does not change the pattern space. The file's content is printed at the end of the current cycle or when the next input line is read (info sed), therefore the N in the following command

sed '/blah Blah/ {
r Bfile
N
}' Afile

Tags:

Regex

Sed