Definite's Extractor

My findings on Life, Linux, Open Source, and so on.

Monthly Archives: January 2008

Multiple files search and replace in Unix

We are told that Unix is very convenient to do various routing and boring jobs.
Multiple files search and replace in one of them.
However, it is not so intuitive for ordinary user to use.

Indeed, there are already plenty web pages show how to do it, but its not easy to remember the long command.
I’ve written a small sh script and found it useful (at least for me).

if [ $# -gt 5 -o $# -lt 4 ]; then
   echo "Usage <basePath> <filenamePattern> <searchPattern> <replaceStr> [separator]"
   exit 1;
if [ $# -eq 5 ]; then

for filename in `find "$1" -name "$2" -type f -print0 | xargs -0 grep -l "$3"`
	echo "File $filename contains pattern, replacing."
	cp $filename $filename.old
	sed -e 's'"${SEPARATOR}$3${SEPARATOR}$4${SEPARATOR}"'g'  $filename 

Save it as and place it in the path you like.

Oh, don’t forget to chmod 755 it.