How to pass a variable containing slashes to sed

buydadip picture buydadip · Jan 5, 2015 · Viewed 76.4k times · Source

How do you pass a variable containing slashes as a pattern to sed?

For example, if I have the following variable:

var="/Users/Documents/name/file"

I want to pass it to sed as so:

sed "s/$var/replace/g" "$file"

However I get errors. How can I circumvent the issue?

Answer

anubhava picture anubhava · Jan 5, 2015

Use an alternate regex delimiter as sed allows you to use any delimiter (including control characters):

sed "s~$var~replace~g" $file