Insert content of a file right after pattern in another file

suppose i have original file:

original.txt:

hello
how are you
you are wonderful
what time is it
I went to the store last night. and some apple juice

then i have another file:

anotherfile.txt:

with my friends mary, john and harry.
We had a great time.
We bought food

Suppose i want to add the content of anotherfile.txt right after the pattern "last night".

so the resulting output looks like this:

hello
how are you
you are wonderful
what time is it
I went to the store last night with my friends mary, john and harry.
We had a great time.
We bought food and some apple juice

I'd like to use awk for this. and the awk code i'm attempting to use is this:

awk '/last.*night/{printf $0; while(getline line<"anotherfile.txt"){print line};next}1' originalfile.txt > resultingfile.txt

for some reason, when i run the above command, it doesn't do anything. it just outputs the original file to resultingfile.txt

To get the output you said you want, we can't follow the directions you gave. Instead we have to replace every occurrence of last night and the character following that (or maybe the <period> following that, or maybe the character following that if the matched string does not appear at the end of an input line) with last night followed by a <space> followed by the contents of anotherfile.txt . Guessing that you meant the 1st of the three possibilities listed above, you could try:

awk '
FNR == NR {
	if(NR == 1)
		rep = $0
	else	rep = rep "\n" $0
	next
}
{	gsub(/last night./, "last night " rep)
}
1' anotherfile.txt original.txt

which produces the output you said you want with the two sample input files you provided.

As always, if you want to try this on a Solaris/SunOS system, change awk to /usr/xpg4/bin/awk or nawk .

1 Like