user3593261
user3593261

Reputation: 568

Replace paragraph in text

How can I use a shell command (sed or awk) to replace a paragraph in a file like the following:

bala bala ba1
balabala.
leave me here.

this paragraph
yes, I'm going
to be replaced

The rest contains
should not be replaced.

After replacing:

bala bala ba1
balaba.
leave me here.

New contains,
I'm replacement!

The rest contains
should not be replaced.

I declare the original contained in a variable $OLD, and new is contained in another variable $NEW.

Upvotes: 1

Views: 2585

Answers (1)

Benjamin W.
Benjamin W.

Reputation: 52281

Assuming you have variables containing your new and old paragraphs, as in

$ echo "$old"
this paragraph
yes, I'm going
to be replaced

and

$ echo "$new"
New contains,
I'm replacement!

You can read the file (assuming it's called infile) into a Bash variable and use parameter expansion:

$ contents=$(< infile)
$ echo "${contents/$old/$new}"
bala bala ba1
balabala.
leave me here.

New contains,
I'm replacement!

The rest contains
should not be replaced.

To change the file in-place:

echo "${contents/$old/$new}" > infile.tmp && mv infile.tmp infile

Upvotes: 5

Related Questions