Escape slashes in shell script variables with sed

sed is a tool of wonder, the in-place replacement (or deletion) of lines in files matching some regexp being my favorite use of it. But some basic functions are quite under-documented (the same old problem of powerful commands having man pages just too long to be read thoroughly).

What I wanted to do is to drop all lines in a file containing a path stored in a variable in my bash script. Problem is, slashes must be escaped for sed to understand that it must treat them as literal, but I have a reference to a variable so I just can’t do something like

sed -i \/path\/to\/delete/d /path/to/file

I found out (on this thread on stackoverflow) that you can use any character you want as separator, and one thing that is usually not known is that you must escape the first occurrence of the separator to have sed use it, unless you are using the s command (replacing patterns, as in sed -i 's/abc/def/' file, while I’m only deleting matches).

So, this is it:

PATH_TO_BE_DELETED="/path/to/delete"
sed -i "\,$PATH_TO_BE_DELETED,d" /path/to/file

I used commas as I know that my paths won’t ever include them, but you can use whatever you want or need.

Note that you also have to use double quotes instead of single ones, or your variable is interpreted as literal!

A nice list of useful one-liners for sed can be found here.

Advertisements

2 thoughts on “Escape slashes in shell script variables with sed

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s