Quantcast
Channel: UNIX and Linux Forums
Viewing all articles
Browse latest Browse all 16232

Insert content of a file into another file before given pattern

$
0
0
I need to insert file x2 into x1 right before first BBB line.
Code:

$ cat x1
AAA    1
AAA    2
AAA    3
BBB    1
BBB    2
BBB    3
$ cat x2
XXX - insert 1
XXX - insert 2

I need to get
Code:

AAA    1
AAA    2
AAA    3
XXX - insert 1
XXX - insert 2
BBB    1
BBB    2
BBB    3

I tried
a)
Code:

$ sed -n '1,/^BBB/p' x1; cat x2; sed -n '/^BBB/,$p' x1
AAA    1
AAA    2
AAA    3
BBB    1
XXX - insert 1
XXX - insert 2
BBB    1
BBB    2
BBB    3

and
b)
Code:

$ sed -e '/^BBB/r x2' x1                                   
AAA    1
AAA    2
AAA    3
BBB    1
XXX - insert 1
XXX - insert 2
BBB    2
XXX - insert 1
XXX - insert 2
BBB    3
XXX - insert 1
XXX - insert 2

Both have problems, (a) inserts after BBB and it duplicates the BBB line, the (b) repeatedly inserts the content and does it again after.

Any ideas?

Viewing all articles
Browse latest Browse all 16232

Trending Articles