search and replace, when found, delete multiple lines, add new set of lines?

hey guys,

I tried searching but most 'search and replace' questions are related to one liners.

Say I have a file to be replaced that has the following:

$ cat testing.txt
TESTING
AAA
BBB
CCC
DDD
EEE
FFF
GGG
HHH
ENDTESTING

This is the input file:

$ cat input.txt
RRR
SSS
TTT

What I want to do is, search testing.txt for "EEE". When I find "EEE", I want to delete "EEE" and two lines below it ending in "GGG". I want to replace "EEE" through "GGG" with the input.txt file. So the ending results will look like:

$ cat testing.txt
TESTING
AAA
BBB
CCC
DDD
RRR
SSS
TTT
HHH
ENDTESTING

I know how to search for single lines of code and replace that line with something else.

How do I say "find this line, delete three lines down, replace it with text from this input file"?

thanks.

---------- Post updated at 02:39 PM ---------- Previous update was at 02:32 PM ----------

I spoke too soon. I did find this post:

It's the very last post of the thread. I'll try that.

Sorry, this should have been in the "Dummies" subforum too. :slight_smile:

nawk 'FNR==NR{f2[++f2c]=$0;next} /^EEE$/{r=1}r && r<=f2c{$0=f2[r++]}1'  input.txt testing.txt
1 Like

That is sick stuff vgersh99...unfortunately i forgot to tell you that my input.txt is a lot longer than 3 lines, say it's 6 lines, but I still don't want to overwrite the HHH.

$ cat input.txt
RRR
SSS
TTT
UUU
VVV

but I still want the "HHH". So this is more like a INSERT and not a overwrite. My bad.

$ cat testing.txt
TESTING
AAA
BBB
CCC
DDD
RRR
SSS
TTT
UUU
VVV
HHH
ENDTESTING

---------- Post updated at 04:25 PM ---------- Previous update was at 03:58 PM ----------

hey guys, actually i found a suggestion that solves one of my two problems.

Make a file, say my.sed, that contains:

s/^%%Page:.*/&\
added line 1\
added line 2\
added line 3\
added line 4/

Add more lines as needed. Then:

sed -f my.sed < infile.ps > outfile.ps

-Rouben Rostamian

I think my question is set. Thanks for looking everyone! Thanks vgersh99 for the sick one liner.

there's no limitation/hard-wiring on the number of lines to be inserted - everythig is driven by the content in your input.txt file. It should work for ANY number of lines.