22 November, 2007

HowTo batch replace string in the set of files

This script replaces all occurrences of 'oldString' with 'newString' in all files in the current directory and all subdirectories.



xqx_replace.sh

#!/bin/bash

if test -z "$1" -o -z "$2"; then
echo Replace all occurrences of 'oldString' with 'newString' in all files in the current directory and all subdirectories.
echo Usage: $0 oldSting newString
exit
fi

OLDSTRING=$1
NEWSTRING=$2

replace() {
echo "$1"
mv "$1" "$1".bak
sed s/$OLDSTRING/$NEWSTRING/g "$1".bak >"$1"
}

check() {
while read; do
if test -n "`grep -l $OLDSTRING \"$REPLY\"`"; then
replace "$REPLY"
fi
done
}

find . -type f |check