Coder Perfect

What is the difference between grep and replace?


I need to recursively scan all files and subdirectories within a directory for a particular string and replace it with another string.

I’m aware that the command to locate it might be as follows:

grep 'string_to_find' -r ./*

But how can I change every occurrence of string to find to anything else?

Asked by billtian

Solution #1

Another way is to use search and then sed to process the results.

find /path/to/files -type f -exec sed -i 's/oldstring/new string/g' {} \;

Answered by rezizter

Solution #2

I found out the answer.

grep -rl matchstring somedir/ | xargs sed -i 's/string1/string2/g'

Answered by billtian

Solution #3

You may also do it this way:


grep -rl 'windows' ./ | xargs sed -i 's/windows/linux/g'

This will search all files in the current directory for the string ‘windows’ and replace ‘windows’ with ‘linux’ for each occurrence of the string.

Answered by Dulith De Costa

Solution #4

On OS X, this works best for me:

grep -r -l 'searchtext' . | sort | uniq | xargs perl -e "s/matchtext/replacetext/" -pi


Answered by Marc Juchli

Solution #5

sed -i’s/string to find/another string/g’ or perl -i.bak -pe’s/string to find/another string/g’ are usually used instead of grep.

Answered by minopret

Post is based on