Definite's Extractor

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

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: