1

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

4 Answers 4

4

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 {} \;
Sign up to request clarification or add additional context in comments.

Comments

2

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.)

Comments

1
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.

Comments

0

Maybe something like this?

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.