Tuesday, June 29, 2010

Using Variables on a sed Expression

Using variables as a matching pattern on a sed expression can be tricky. Take a look at the examples below.

Here's the value for PATH and HOME on this example system:
$ echo $PATH
/home/victor/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
$ echo $HOME
/home/victor

Let's say we would like to use the value of HOME to change the string “/home/victor/bin” to “/bin”. A few attempts would look like this:
$ echo $PATH | sed 's/"$HOME"//'
/home/victor/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games

$ echo $PATH | sed 's/$HOME//'
/home/victor/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games

$ echo $PATH | sed s/$HOME//
sed: -e expression #1, char 9: unknown option to `s'

However if we use a colon “:” as the field delimiter instead of a forward slash “/”, the desired result can be achieved very easily:

$ echo $PATH | sed s:$HOME::
/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games

3 comments:

楊鳳苓 said...

IS VERY GOOD..............................

DamoSuRFeR! said...

Thanks! I've been scratching my head as to why my 's/$HOME//' didn't work!

It didn't occur to me that the /'s in the path name were interfering with the delimiters, but it makes perfect sense.

Anonymous said...

I just spent over an hour slogging through extensive and tedious explanations of how to do this on other web sites, and I was growing mighty weary. I was just about to give up, the sun was setting, and my sed command was still failing. My format matched those other web sites, who invariably claimed the correct syntax and the intellectual high ground in a subtley condescending manner. Your explanation got me to the best solution: the one that works! And I got the answer quickly, with no attitude. Thank you!