How to grep and replace – Dev

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


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?


I got the answer.

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


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' {} \;


This works best for me on OS X:

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



You could even do it like this:


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.