How to grep and replace – Dev

The best answers to the question “How to grep and replace” in the category Dev.

QUESTION:

I need to recursively search for a specified string within all files and subdirectories within a directory and replace this string with another string.

I know that the command to find it might look like this:

grep 'string_to_find' -r ./*

But how can I replace every instance of string_to_find with another string?

ANSWER:

I got the answer.

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

ANSWER:

Another option is to use find and then pass it through sed.

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

ANSWER:

This works best for me on OS X:

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

Source: http://www.praj.com.au/post/23691181208/grep-replace-text-string-in-files

ANSWER:

You could even do it like this:

Example

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

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