How to insert file contents after nth occurrence of a string using sed?

Hi,
I would like to know how, using sed, be able to insert contents of file2 in file1 after say the second occurrence of a given string? e.g.

> cat file1
banana
apple
orange
apple
banana
pear
tangerine
apple 

> cat file2
I don't like apples

What would be the sed command to insert the contents of file2 after the second occurrence of apple in file1? i.e the output would be:

banana
apple
orange
apple
I don't like apples
banana
pear
tangerine
apple 

Thanks in advance..

You can try with like this also . I am not using

sed

here.

awk -v place=`awk '$1~/apple/ {a=a+1;if(a==2){b=NR}} END {print b} ' file1` '{ if(FILENAME == "file1" && NR <=place) { print }; if(FILENAME == "file2") { print }}' file1 file2 > outputfile
awk -v place=`awk '$1~/apple/ {a=a+1;if(a==2){b=NR}} END {print b} ' file1` '{ if(FILENAME == "file1" && NR >place) { print }}' file1 >> outputfile

.

output is like this with number of occurance 2 .

cat outputfile
banana
apple
orange
apple
I don't like apples
banana
pear
tangerine
apple
1 Like

Try

sed '1,/apple/{p;d}; /apple/,$ {1,1 r file2
}' file1
banana
apple
orange
apple
I don't like apples
banana
pear
tangerine
apple 
1 Like
[akshay@nio tmp]$ cat file1.txt
banana
apple
orange
apple
banana
pear
tangerine
apple
[akshay@nio tmp]$ cat file2.txt
I don't like apples
[akshay@nio tmp]$ awk '$0 ~ pattern{++c}1 ; c==occurence && !f{f=1; while(getline < content){ print }close(content) }' pattern='apple' occurence='2' content='file2.txt'  file1.txt

Resulting

banana
apple
orange
apple
I don't like apples
banana
pear
tangerine
apple
1 Like

Thank you all so very much!

Thank you all for your replies; much appreciated.