Tuesday, March 12, 2013

Find,replace in multiple files using BASH

Another of those zillions of tweaks that I am afraid will slip out of my head! So jotting it down here.

When you are editing HTML files, or some similar content template with multiple changes to be done in a huge number of files, it is simply excruciating to dig into each of the files and search for a pattern and change it.

For instance, if you have a host of html files, and you need to maybe make one common change in all files, the simplest thing to do is use the power of BASH!

To change a string, recursively in multiple files, use the following command.

raghav@fossphosis:~$grep -rl 'old-string' ./ | xargs sed -i 's/old-string/new-string/g'

'grep' as always performs pattern matching
'sed' is used as the stream editor

Old-string is the string to be changed, into new-string.

May the power of BASH be yours!
GNU Rocks.

No comments:

Post a Comment