5
1
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?
5
1
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?
10
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 {} \;
10
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.
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
1
If you want more control you could use a python script like:
1-1 this is going to modify every file in the directory, even if it doesn't contain the word you want to replace. – dogbane – 2011-08-17T14:08:53.250
@dogbane Yep, just as indicated in the sentence above the command. – Michael – 2011-08-17T14:09:38.110
hey man...magic worked...!!! thank you.....you have saved ma lot time.......... – None – 2011-08-17T14:11:11.363