I'm trying to write a simple bash function to search-and-replace recursively down a directory, changing one string to another. Here's what I've got:
function sar () {
from="$1"
shift
to="$1"
shift
if [[ $from == '' || $to == '' ]]
then
echo Usage: sar \<from\> \<to\> \<filename\>
return
fi
while [[ $# -gt 0 ]]
do
filename="$1"
shift
find ./$filename -type f -exec sed -i -e 's/$from/$to/g' {} \;
done
}
For example:
$ sar xxxx yyyy mydir
should run a find
in ./mydir and substitute xxxx to yyyy in every file it visits. The command runs, produces no error, but does not perform any substitutions.
Running with set -x
, I see
+ find ./mydir -type f -exec sed -i -e 's/$from/$to/g' '{}' ';'
$from
and $to
weren't resolved, and some extra quoting has appeared.
What is the proper way to write that command within a bash function (which I assume obeys the same syntax rules as a bash script)?