1

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)?

1 Answer 1

4

Variables are not expanded when put inside single quotes, you need to use double quotes instead:

... sed -i -e "s/$from/$to/g" ...
1
  • 1
    Just be very careful about sar a/from/string a/to/string . Commented Aug 31, 2016 at 22:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .