Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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?

share|improve this question

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

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

add comment

4 Answers 4

up vote 8 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 {} \;
share|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
add comment

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.

share|improve this answer
add comment

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|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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