CuriousBug
CuriousBug

Reputation: 243

Insert contents of a file against a pattern using sed

I want to insert contents of a file after a pattern matches. I have tried the following command but it didn't work

sed '/ghi\(\)/ r file2.txt' file1.txt

The contents of file1.txt are:

abc
def
ghi()
jkl

The contents of file2.txt are:

hello world!
my name is xyz
i live in abc city

The desired output : I want the content of file1.txt to become:

abc
def
ghi()
hello world!
my name is xyz
i live in abc city
jkl

Am I missing any parameter? How to achieve this?

Upvotes: 1

Views: 65

Answers (2)

ZNZNZ
ZNZNZ

Reputation: 376

you need -i to make replacement in place, and you can also use .bak to make a .bak backup file

sed -i.bak '/ghi\(\)/ r file2.txt' file1.txt

it will change file1.txt content and create file1.txt.bak for backup

Upvotes: 2

RavinderSingh13
RavinderSingh13

Reputation: 133428

you could run following awk may help you on same.

awk '/ghi()/{print;system("cat file2.txt");next} 1' file1.txt

Also following sed too worked fine for me, I have GNU sed 4.2.1

sed '/ghi()/r file2.txt' file1.txt

Upvotes: 0

Related Questions