One of the ways replacing a string with sed can be done as follows:

sed -i 's/old_str/new_str/' file.txt

However if replace.sh is

 sed -i 's/$1/$2/' $3

the command ./replace.sh old_str new_str file.txt doesn't seem to work -- after making replace.sh executable of course. Why is that?

I am aware rpl does exactly the same as I intend to do with replace.sh, but I'd like to understand why is it not working.

  • 1
    You're hitting a quoting issue. The single quote ' character prevents $1 from being expanded and you have the literal string $1. If you use "" instead then it'll work... but beware of magic characters in a solution like this; ./replace.sh my/string new/stuff myfile won't work! – Stephen Harris Mar 30 at 22:57
  • Do you have any suggestions on how to fend off the issue regarding magic characters? Thank you! – Sphery Mar 30 at 23:09

There is no parameter expansion inside single quotes (see this previous answer on stackoverflow)

echo '$toto'
> $toto
echo "$toto"
> 1

Simply replace your single quotes with double quotes and your script will do what you expect.

Not the answer you're looking for? Browse other questions tagged or ask your own question.