capser
capser

Reputation: 2635

Sed special characters

I wanted to change out the home directory that I has in some files. I figured that I would have to escape the curly brackets - like this :

sed -i 's/\$\{HOME\}/\/casper\/home/g' /var/tmp/casper.txt

Everything that I experience in sed tells me that I would have to escape the brackets, but I did not. The only thing that I needed to escape is the Dollar sign. What kind of regex engine does sed use and where is a list of the special characters that need to be escaped and what not does not need to be escaped.

sed -i 's/\${HOME}/\/casper\/home/g' /var/tmp/casper.txt

Upvotes: 1

Views: 101

Answers (1)

Bartłomiej
Bartłomiej

Reputation: 1078

I am not an expert, just an user of regexps, so I cannot give you strict technical answer, but according to info sed, if invoked without -r (--regexp-extended), than it uses basic regular expressions. If -r is put, then extended regular expressions are used. There is an explanation in info's Appendix:

The only difference between basic and extended regular expressions is in
the behavior of a few characters: '?', '+', parentheses, braces ('{}'),
and '|'.  While basic regular expressions require these to be escaped if
you want them to behave as special characters, when using extended
regular expressions you must escape them if you want them _to match a
literal character_.

By the way, if you need to put a slash inside sed's regex, it is very useful to use different symbol as a separator. It doesn't need to be a slash, you can choose the symbol arbibtrary, for example it could be @. So instead this:

sed -i 's/\${HOME}/\/casper\/home/g' /var/tmp/casper.txt

you can make this:

sed -i 's@\${HOME}@/casper/home@g' /var/tmp/casper.txt

Upvotes: 1

Related Questions