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).

#!/bin/sh
if [ $# -gt 5 -o $# -lt 4 ]; then
   echo "Usage searchReplace.sh <basePath> <filenamePattern> <searchPattern> <replaceStr> [separator]"
   exit 1;
fi
SEPARATOR=/
if [ $# -eq 5 ]; then
	SEPARATOR=$5
fi

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

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

Oh, don’t forget to chmod 755 it.