Ali
Ali

Reputation: 632

replace all lines which contain a certain word with a new word in all PHP files in a folder

Assume I have a folder with many php files in it, and some of those php files have a line that has a specific word, i need a linux command line which find all files which have that lines(which contains a specific word) and replace that lines with another word for example:

     $source = $_FILES['fupload']['tmp_name'];
     $target = "upload/".$_FILES['fupload']['name'];
     move_uploaded_file( $source, $target );// or die ("Couldn't copy");
     $size = getImageSize( $target );

in above code which is part of a php file, assume that specific word is "fupload" and we want replace that line with "echo" after running linux command line it becomes this one:

     echo
     $target = "upload/".$_FILES['fupload']['name'];
     move_uploaded_file( $source, $target );// or die ("Couldn't copy");
     $size = getImageSize( $target );

and this process executes for all phph files which have this situation.

I found this code but this code only removes lines which contains specific word but I need to replace whole of those lines with another word:

      find /var/www/website -type f -exec sed -i '/$vjfegamd/d' {} ';'

Upvotes: 1

Views: 66

Answers (1)

SLePort
SLePort

Reputation: 15461

To replace only the first occurence of fupload(as in your sample code), try this:

find . -name '*.php' -print0 -exec sed -i.bak '0,/fupload/c echo' {} \;

The c command changes the whole line with the string following the command.

Before editing, all files are saved with a .bak extension.

As some sed flavors require c to be followed with a new line, you can try this one for the same result:

find . -name '*.php' -print0 -exec sed i.bak '0,/fupload/s//echo/' {} \;

Upvotes: 1

Related Questions