Recursive Search/Replace Text from Terminal

This came in handy for myself the other day and I figured it might come in handy for some of you out there. This is a quick command that will recursively do a find and replace for certain keywords by using a combination of grep and sed. Basically, we search recursively using grep and then we pipe in the filenames into sed for the string replacement.

grep -Irl keyword . | xargs sed -i 's/keyword/replacement/g'

Here’s a breakdown of the options used (I’ll assume you’re familiar with xargs and piping):

grep -I will ignore binary files
grep -r is recursive
grep -l will spit out the filename only
sed -i will edit the files in place

Feel free to donate if this post prevented any headaches! Another way to show your appreciation is to take a gander at these relative ads that you may be interested in:

There's 2 Comments So Far

  • Pawan
    September 9th, 2011 at 6:32 am

    I tried it.. but it searches the files with keyword and says permission denied. Should I change the permissions of all the files on the server to 777..?? Or do I have better option than that. Thanks in advance. 🙂

  • [email protected]
    September 9th, 2011 at 8:08 am

    You certainally could just change the permissions of all the files, but I would make sure they are set back to the proper perminssions when finished. chmod 655 would be better than chmod 777, but it doesn’t much matter if you’re going to change it back anyways.

    If you can edit and save the files in, say, VI/VIM/Emacs/Nano/Touch, you should be able to run sed -i on them.

Share your thoughts, leave a comment!