I have a file like this:
foo and more
stuff
various stuff
variable number of lines
with a bar
Stuff I want to keep
More stuff I want to Keep
These line breaks are important
I want to replace everything between foo and bar so that I get:
foo testtext bar
Stuff I want to keep
More stuff I want to Keep
These line breaks are important
as recommended in another thread I tried:
sed -e '/^foo/,/^bar/{/^foo/b;/^bar/{i testtext' -e 'b};d}' file.txt
Is there a more general-purpose solution to find and replace everything between foo
and bar
, absolutely no matter what it is?
You can use the following
sed
script:replace.sed:
Call it like this:
Output:
If you want to pass the begin and ending delimiter using a shell script you can do it like this (comments removed for brevity):
The above works as long as
$start
and$end
won't contain regex special characters, to escape them properly use the following code: