Sed: replace text block

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

Replace:

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

WITH

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

So, I'm trying to map the block to sed 's/<?php\n$r = session_start();/<?php\nheader... but it does not work.

I would appreciate help in what is happening here and how to do it. I am going to do this with python.

Thanks!

+4
source share
3 answers

This may 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 in one line:

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

One way: sed :

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

Just add the block of text you want to add to each file in block.txt . The sed component simply removes the lines between the first line and the corresponding pattern.

0
source

sed, slightly changed your decision:

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

Source: https://habr.com/ru/post/1441737/


All Articles