PHP and Sed for String Substitution

Notice: wpdb::escape is deprecated since version 3.6! Use wpdb::prepare() or esc_sql() instead. in /var/www/wphost/wp-includes/functions.php on line 3201 Notice: wpdb::escape is deprecated since version 3.6! Use wpdb::prepare() or esc_sql() instead. in /var/www/wphost/wp-includes/functions.php on line 3201

I needed to replace a string in several thousand files scattered all over the filesystem on one of our servers. I used find to create a list of files that needed to be changed, along with their complete path and called it “list.txt”. It looked something like this:


/path/to/file/one/fileone.html
/path/to/file/two/filetwo.php
/path/to/file/three/filethree.htm
/path/to/directory with spaces/filefour.txt
and so on...

I worked out the “sed” command to do the in place editing, and Zach helped me whip up a quick PHP script to read the contents of “list.txt” into an array and iterate through it. He was also nice enough to show me how to use “str_replace” to escape any annoying spaces that happened to find their way into the names of directories.

  1. < ?php
  2. $files=file('list.txt');
  3.         foreach($files as $file)
  4.         {
  5.         $command='/bin/sed -i \'s/old-string/new-string/g\' '.str_replace(' ','\ ',$file);
  6.         exec($command);
  7.         }
  8. ?>

It’s a handy little script that I’m sure I will find a use for later, so I thought I would put it up here.

3 thoughts on “PHP and Sed for String Substitution

  1. Thanks for the tip. However, with php, “sed -i” does not edit file in place on my system. I also tried passthru and system but they don’t work neither. sed (without -i option) displays the proper replacement. “sed -i” on command line works (it edits file in place). So there is something about passing the -i option in php that doesn’t work.

  2. Ignore my first comment…I found the reason that sed -i doesn’t work. I don’t have write access to the directory that sed create a temp file in.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>