Saturday, October 24, 2009

Using variable with sed inside a shell script

For using sed inside a shell script, The variable should be in "double quotes" and the command in 'single quotes'. Following is the example

#!/bin/bash

usage () {
echo "$0 -s < name
> -r <replace name> -f <file name>"
exit
}

while getopts s:r:f: option
do
case "$option" in
s) search="$OPTARG";;
r) replace="$OPTARG";;
f) filename="$OPTARG";;
\?) usage
esac
done

sed -i 's/'"$search"'/'"$replace"'/g' "$filename"

No comments: