tags:

views:

134

answers:

4

Hello I have a colleague of mine who is a procedural code developer and has same smtp server name sitting in 120 different files, now I have to change them to something else. But doing that one by one would be impossible. I am using "grep" to recursively search for a string in all the files sitting in that directory. But I am not sure if grep can edit the file and replace it with the new string.

Thanks

+1  A: 
find /directory -type f -exec sed -i 's/oldname/newname/g' {} +

Searches recursively through /directory and uses sed to do a search and replace. The {} is replaced by the file names that are found.

John Kugelman
A: 

Maybe something like this?

find /path/to/start/from/ -type f | xargs perl -pi -e 's/textToFind/TextToReplace/g'

Byron Whitlock
+3  A: 

Shouldn't this be on serverfault?

Anyway, you should be looking at a combination of find and sed.

Possibly something like:

find . -iname "<filepattern>" -exec sed -e "s/<regex to look for>/<replacement>/g" -i {} \;
gpampara
A: 

Use sed.

grep -rl smtp1.example.com . | xargs sed -i 's/smtp1.example.com/smtp2.example.com/g'

which means find all files containing smtp1.example.com; output their names; pass each filename to the sed command, which does a search-and-replace on each file.

grep will only list files that actually contain the text; this minimises the number of files for which sed is invoked. (Using find -type f results in sed being invoked on any file.)

Richard Fearn