Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a variable containing slashes to sed

Tags:

bash

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.


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

Using / in sed as a delimiter will conflict with the slashes in the variable when substituted and as a result you will get an error. One way to circumvent this is to use another delimiter that is unique from any characters that is in that variable.

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

you can use the octothorpe character which suits the occasion (or any other character that is not a / for ease of use)

sed "s#$var#replace#g" 

or

sed 's#$'$var'#replace#g'

this is suitable when the variable does not contain spaces

or

sed 's#$"'$var'"#replace#g'

It is wiser to use the above since we are interested in substituting whatever is in that variable only as compared to double quoting the whole command which can cause your shell to interpet any character that might be considered a special shell character to the shell.