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?

link|improve this question

feedback

migrated from stackoverflow.com Aug 17 '11 at 17:36

This question came from our site for professional and enthusiast programmers.

4 Answers

up vote 7 down vote accepted

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 {} \;
link|improve this answer
-1 this is going to modify every file in the directory, even if it doesn't contain the word you want to replace. – dogbane Aug 17 '11 at 14:08
@dogbane Yep, just as indicated in the sentence above the command. – Michael Aug 17 '11 at 14:09
hey man...magic worked...!!! thank you.....you have saved ma lot time.......... – Mr.32 Aug 17 '11 at 14:11
feedback

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.

link|improve this answer
feedback

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

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

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