Bash script to replace a word or a string in multiple files at once
There are multiple ways of replacing a word or a string with another in a stream of input. Here, in this article, we use “sed” command. While the “sed” command operates on one file at a time, the bash script takes care of iterating it through multiple files and making backups of original files. Run the following script with no arguments to view help.
#!/bin/bash
usage() {
echo Usage: $0 str-from str-to files
echo e.g: $0 "this string" "that ring" file1.txt file2.txt file3.txt
exit 1
}
if [ "$1" == "" ] || [ "$2" == "" ] || [ "$3" == "" ]; then
usage
fi
STR_FROM=$1
shift
STR_TO=$1
shift
FILES=$*
TFILE="/tmp/out.tmp.$$"
for f in $FILES
do
if [ -f $f -a -r $f ]; then
/bin/cp -f $f $f.orig
sed "s/$STR_FROM/$STR_TO/g" "$f" > $TFILE && mv $TFILE "$f"
else
echo "Error: Cannot read $f"
fi
done
rm -f $TFILE
As the “str-from” and “str-to” are passed to sed command as is, more sophisticated regular expressions can be used to get the more complex work done.
Recent Comments