Monday, April 28, 2014

Replace a String in Multiple Files in Linux Using Grep and Sed

So, I had to refactor my code and replace the occurrence of a particular text with another. The problem was that, the text to replace occurred in multiple files spanning various directories. So I used grep to find the word and if it finds it to run sed to replace the text.

The format is as follows:
grep -rl stringToFind somedir/ | xargs sed -i 's/stringToFind/replacementString/g'

For example: I wanted to replace the string 'SCOpe' with 'SCOPE'. The following is what I used:
grep -rl 'SCOpe' ./ | xargs sed -i 's/SCOpe/SCOPE/g'
This will search for the string 'SCOpe' in all files relative to the current directory and replace 'SCOpe' with 'SCOPE' for each occurrence of the string in each file.