Tuesday, November 27, 2012

Search and replace text in multiple files

It's very common task to find some text in some files and replace it. Here is my recipe to deal with it

In this example I will find all 'varchar' text in my '.sql' files and replace it with 'char'.
At first let's search for the files that contain the text:
grep -i 'varchar' *.sql
In the output you can see the list of files with corresponding match within it.
Now let's take this list of files and replace the searched text within with the new one:
grep -il 'varchar' *.txt | xargs sed -i 's/varchar/char/gi'
This was a case-insensitive case. But if you need to be case-sensitive then use:
grep -l 'varchar' *.txt | xargs sed -i 's/varchar/char/g'