insert file2 after line containing patternX in file1

file1:-
aaaa
bbbb
cccc
dddd
eeee

file2:-
1111
2222
3333
4444

I want to insert file2 after pattern bbbb to come up with a finished file of :-
aaaa
bbbb
1111
2222
3333
4444
cccc
dddd
eeee

I have it working using grep-n/head/tail but it looks horrible.

thoughts?

HI.

There is a sed sub-command to insert a file:

       r filename
              Append text read from filename.
-- excerpt from man sed

See if you can create a complete sed command to find the appropriate line in the first file and use "r" to get the second file inserted at that point ... cheers, drl

ok i found something that works.

ed -s file1 <<< $'/bbbb/ r file2\n,p' # to stdout
or
ed -s file1 <<< $'/bbbb/ r file2\n,w' # to directly update file1

results in the output being:-
aaaa
bbbb
1111
2222
3333
4444
cccc
dddd
eeee

which is much neater than what i had, however now i would like to have the file names as variables as per :-
f1=file1
f2=file2
ed -s $f1 <<< $'/bbbb/ r $f2\n,p'

which results in :-
?$f2

ie not resolving the $f2 variable.... so i changed the quotes to doubles :-
$ ed -s $f1 <<< $"/bbbb/ r $f2\n,p"
?file2\n,p

so its resolving $f2 but failing syntax in ed for some reason...

anyone know how to resolve this?

sigh, wish i had checked sed first....

$ sed "/bbbb/ r $f2" < $f1
aaaa
bbbb
1111
2222
3333
4444
cccc
dddd
eeee

The last step is to get the file inserted BEFORE the pattern..... using sed, if my pattern is bbbb can i get the output to look like ?? :-
aaaa
1111
2222
3333
4444
bbbb
cccc
dddd
eeee

Hi.

As you likely know, you would need some kind of memory to be able to insert before a specific line. The memory would contain the line of interest, you would cause the second file to be inserted, and then you would cause the line of interest to be printed.

There is a basic memory facility in sed. It's called the hold space (to differentiate it from the normal pattern space).

Have you tried to use that yet? ... cheers, drl

f1=file1
f2=file2

ed -s $f1 <<EOF
/bbb/r $f2
w
q
EOF