Friday, June 06, 2008

sed trick

If your sed regular expression pattern contains "/", it will break sed because it will think that you are trying to terminate the command premature. You can try to use other character to replace "/", if not you have to escape the "/" with "\/". See below for illustration:
$ echo "/home/chihung/bin" | sed -e "s/\/home\/chihung/\/user\/chchan/"

$ echo "/home/chihung/bin" | sed -e "s#/home/chihung#/user/chchan#"

One caveat, if you use "!" to replace "/" within the double quote expression pattern, sed in an interactive bash shell will complain because the shell will interpret "!" as if you are trying to access the history event. Shell will not parse single-quoted string and therefore sed expression pattern using "!" as separator is fine. See below:

$ echo "/home/chihung/bin" | sed -e "s!/home/chihung!/user/chchan!"
bash: !/home/chihung!/user/chchan!": event not found

$ echo "/home/chihung/bin" | sed -e 's!/home/chihung!/user/chchan!'

$ cat
#! /bin/sh
echo "/home/chihung/bin" | sed -e "s!/home/chihung!/user/chchan!"

$ ./



Post a Comment

<< Home