0

I want to replace all files (foo.php as example) that contain certain string 'bar' with a backup foo.php file, which is located in ./backup/foo.php. How can I do that?

I know if I grep -lrI foo . all files will be listed, but how to replace them?

  • You should start using a VCS instead of "source backups". git is a good one. – gronostaj Jun 15 '15 at 16:14
  • That's not necessary. To make long story short: After Wordpress site was hacked, I just need to replace index.php files which were added to every catalog of Wordpress. – MattPL Jun 15 '15 at 17:01
1

The following line of bash will do, assuming you just want to get rid of these files:

   for i in $(grep -lrI bar); do mv -i ./backup/`basename $i` $i; done
1

You could try with the following format

Syntax :

grep -rl matchstring somedir/ | xargs sed -i 's/string1/string2/g'

The example would be :

grep -rl 'windows' ./ | xargs sed -i 's/windows/linux/g'

This will search for the string windows in all files relative to the current directory and replace 'windows' with linux for each occurrence of the string in each file.

Additional Note from comment : The forward slash '/' delimiter in the sed argument could also be a different delimiter (such as the pipe '|' character). The pipe delimiter might be useful when searching through a lot of html files if you didn't want to escape the forward slash.

In addition to that you could try kev method

cd /path/to/your/folder
sed -i 's/foo/bar/g' *

Occurrences of "foo" will be replaced with "bar".

  • 1
    OR pipe that grep to a file and use it (useful for checking before making changes especially on production / enterprise systems.) – linuxdev2013 Jun 15 '15 at 14:26
  • I did like you wrote. I needed to re-make it a few times in order to change strings that were in separate lines. Or maybe there is a solution, that can change many strings at once? – MattPL Jun 15 '15 at 17:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.