sed: replace a block of text

2020-06-05 01:42发布

问题:

I have a bunch of files, starting with a block of code and I'm trying to replace with another.

Replace:

<?php
$r = session_start();
(more lines)

With:

<?php
header("Location: index.php");
(more lines of code)

So im trying to match the block with sed 's/<?php\n$r = session_start();/<?php\nheader... but it doesn't work.

I would appreciate help in what is happening here and how to achieve this. I'm thinking in doing this with python instead.

Thanks!

回答1:

This might work for you (GNU sed):

sed -i '1i\
This is a\
new block of\
code
1,/$r = session_start();/d' file 

Or if you prefer to place the new code in a file:

sed -i '1r replacement_code_file
1,/$r = session_start();/d' file

All on one line:

sed -i -e '1r replacement_code_file' -e '1,/$r = session_start();/d' file


回答2:

One way using sed:

cat block.txt <(sed '1,/$r = session_start();/d' file.txt) > newfile.txt

Simply add the block of text you'd like to add to each file to block.txt. The sed component simply deletes lines, between the first line and a matching pattern.



回答3:

sed, tweaked your solution a little bit:

sed  '/<?php/{N;s/\n$r = session_start();/\nheader(\"Location: index.php\");/}' file