How to pass a variable containing slashes to sed

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

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

As mentioned above we can use control character as delimiter as well like:

sed "s^[$var^[replace^[g" file

Where ^[ is typed by pressing Ctrl-V-3 together.

Or else in bash shell you can use this sed with \03 as delimiter:

d=$'\03'
sed "s${d}$var${d}replace$d" file

A pure bash answer: use parameter expansion to backslash-escape any slashes in the variable:

var="/Users/Documents/name/file"
sed "s/${var//\//\\/}/replace/g" $file

Tags:

Regex

Bash

Sed