[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: escape characters in sed



Hans du Plooy wrote:

Typo, sorry.  Should be:

sed 's/\\(/ /'


Still doesn't work though :-) I guess the question should be, how to excape a ( character?

With a backslash!  The thing is, if you include the single quotes,
you don't need to escape it through the shell, but if you drop
the single quotes, you do. Also, since you are escaping the backslash to sed, you are telling sed to look for a literal backslash. When sed sees an unescaped (, it looks for it literally. When it sees an escaped
(, it uses it as a grouping symbol.  In other words:  the shell and
sed both treat backslash as a special character, but only the shell
treats ( as a special character.

Suppose you want to replace the literal text "a (fat) cat"
with "a cat":
$ echo "a (fat) cat" | sed 's/(fat) //'
a cat

However, this replaces all occurences of "(fat) ", which may not
be what you want, so you do a grouping:
$ echo "a (fat) cat" | sed 's/\(a\) (fat) \(cat\)/\1 \2/'
a cat

Here, we use '(' to match literal '(', and '\(' to tell
sed that we want to remember that portion of the regex,
for use in the replacement string.



Reply to: