4

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!

jam
  • 75
  • 1
  • 1
  • 7
  • Is there any extra information you can add? By the looks of things you only want to change the second line in each of your files. Is that correct? – Steve Oct 24 '12 at 06:44
  • Is more than the second line, it's a block of code, an old code I would like to replace (about 4 or 6 lines at the start of every file) – jam Oct 24 '12 at 06:51
  • This is not working for me. I'm trying to get block of text replaced by other and can't do it with this sed example you provided. This is what I would like to do, match block of text and replace it with another. In this example I would like to replace block of text that is: "line 2 original text line 1 line 2 line 3 – valentt Sep 03 '13 at 10:21

3 Answers3

3

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
potong
  • 55,640
  • 6
  • 51
  • 83
0

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.

Steve
  • 51,466
  • 13
  • 89
  • 103
0

sed, tweaked your solution a little bit:

sed  '/<?php/{N;s/\n$r = session_start();/\nheader(\"Location: index.php\");/}' file
Guru
  • 16,456
  • 2
  • 33
  • 46