How to pass a variable containing slashes to sed How to pass a variable containing slashes to sed bash bash

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


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


Another way of doing it, although uglier than anubhava's answer, is by escaping all the backslashes in var using another sed command:

var=$(echo "$var" | sed 's/\//\\\//g')

then, this will work:

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