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/"
/user/chchan/bin

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

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!'
/user/chchan/bin

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

$ ./a.sh
/user/chchan/bin

Labels:

0 Comments:

Post a Comment

<< Home