find and replace command for whole directory

22,318

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

Share:
22,318

Related videos on Youtube

Jeegar Patel
Author by

Jeegar Patel

Updated on September 18, 2022

Comments

  • Jeegar Patel
    Jeegar Patel over 1 year

    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?

  • dogbane
    dogbane over 12 years
    -1 this is going to modify every file in the directory, even if it doesn't contain the word you want to replace.
  • Michael
    Michael over 12 years
    @dogbane Yep, just as indicated in the sentence above the command.
  • Sebastian Zartner
    Sebastian Zartner over 12 years
    hey man...magic worked...!!! thank you.....you have saved ma lot time..........