I have learned that whene I use the command grep then I must mask those characters {,},(,)
and |
But I have found now an example, where /
was masked!
Which characters must be masked when using grep and sed command?
-
define: "masked". If you mean *escape*, this may be interesting to read [Which characters need to be escaped in Bash? How do we know it?](http://stackoverflow.com/q/15783701/1983854). – fedorqui Jun 10 '16 at 09:44
-
It depends which mode of `grep`/`sed` you use. `grep 'pattern'`? `grep -P 'perl-pattern'`? – Willem Van Onsem Jun 10 '16 at 09:45
-
for example how would you look for /*.....*/ – Joe Jun 10 '16 at 09:46
-
I'm using grep 'pattern' – Joe Jun 10 '16 at 09:50
-
`/` needs to be escaped only inside of sed's `/.../` or `s/.../.../`. It usually cleaner to switch to a different character, though. – choroba Jun 10 '16 at 09:52
-
@choroba so in this case can I write : grep \{/*}[0-9A-Za-z]*\{*/\} ? – Joe Jun 10 '16 at 09:55
-
Why `\{`? What about spaces, commas etc. inside of the comments? You also need to backslash asterisks. – choroba Jun 10 '16 at 09:57
-
@choroba grep \{/*\}[0-9A-Za-z]*\{*/\} Could you please tell me the true command for looking for the comment, I think it will helps me better to understand the problem ! – Joe Jun 10 '16 at 10:01
-
`grep '/\*.*\*/'` might work, but only for single-line comments. – choroba Jun 10 '16 at 10:09
-
Thank you! so you did mask or escape the * with \ is that right? – Joe Jun 10 '16 at 10:21
1 Answers
When writing regexes in a shell script, it is normally sensible to enclose the regex in single quotes. Then you don't have to worry about anything except single quotes that appear in the regex itself. Occasionally, it may make sense to enclose the regex in double quotes (if it involves matching single quotes and not matching double quotes), but then you have to be careful about $
, the back-quote `
, and backslashes \
.
So:
grep -e '^.*([a-z]*)[[:space:]]*{[^}]*}$'
With sed
, you need to worry about s///
operations when the search or replacement pattern itself contains slashes /
. The simplest technique is to use an alternative character such as %
:
sed -e 's%/where/it/was/%/it/goes/here/now/%'
There are three or four dialects of grep
:
- Plain
grep
- Extended
grep
(grep -E
, once upon a time known asegrep
) - Fixed
grep
(grep -F
, once upon a time known asfgrep
) - Sometimes you get
grep
with PCRE (Perl-compatible Regular Expression) support:grep -P
.
Even within 'plain grep
', you can find there is some variability between implementations.
Similarly, there are two main dialects of sed
:
- Plain
sed
- Extended
sed
(sed -E
orsed -r
;sed -E
is more widely available)
You need to read about POSIX BRE (basic regular expressions), supported by plain grep
and plain sed
, and POSIX ERE (extended regular expressions), supported by grep -E
and sed -E
(when EREs are supported by sed
at all).

- 730,956
- 141
- 904
- 1,278