Wednesday, May 1, 2019

Linux: find and replace text across multiple lines


For example, we have a file myfile.txt with the following content:

This is
my
apple
in
the basket.

We can run this command:

$ perl -0777 -i -pe 's/This is\nmy\napple/These are\nmy\napples/g' myfile.txt

to change the content of the file into:

These are
my
apples
in
the basket.

The option -0777 applies the matching to the whole file instead of line by line. The option -i makes the changes in place.

No comments:

 
Get This <