find and replace command for whole directory

Is there any command in Linux which will find a particular word in all the files in a given directory and the folders below and replace it with a new word?


Solution 1:

This will replace in all files. It can be made more specific if you need only a specific type of file. Also, it creates a .bak backup file of every file it processes, in case you need to revert. If you don't need the backup files at all, change -i.bak to -i.

find /path/to/directory -type f -exec sed -i.bak 's/oldword/newword/g' {} \;

To remove all the backup files when you no longer need them:

find /path/to/directory -type f -name "*.bak" -exec rm -f {} \;

Solution 2:

You can use the following command:

grep -lR "foo" /path/to/dir | xargs sed -i 's/foo/bar/g'

It uses grep to find files containing the string "foo" and then invokes sed to replace "foo" with "bar" in them. As a result, only those files containing "foo" are modified. The rest of the files are not touched.

Solution 3:

Not a single command but combination of several:

find /home/bruno/old-friends -type f -exec sed -i 's/ugly/beautiful/g' {} ;

Example from here

Solution 4:

If you want more control you could use a python script like:

  • http://xahlee.org/perl-python/find_replace_unicode.html
  • http://code.activestate.com/recipes/473828-regexplace-regular-expression-search-and-replace/