linux - How to grep and replace

ID : 10057

viewed : 29

Tags : linuxgrepreplacelinux

Top 5 Answer for linux - How to grep and replace

vote vote

100

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

80

I got the answer.

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

78

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.

vote vote

69

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

vote vote

54

Usually not with grep, but rather with sed -i 's/string_to_find/another_string/g' or perl -i.bak -pe 's/string_to_find/another_string/g'.

Top 3 video Explaining linux - How to grep and replace

Related QUESTION?