Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do you have to escape | and + in grep between apostrophes?

I was under the impression that within single quotes, e.g. 'pattern', bash special characters are not interpolated, so one need only escape single quotes themselves.

Why then does echo "123" | grep '[0-9]+' output nothing, whereas echo "123" | grep '[0-9]\+' (plus sign escaped) output 123? (Likewise, echo "123" | grep '3|4' outputs nothing unless you escape the |.)

This is under bash 4.1.2 and grep 2.6.3 on CentOS 6.5.

like image 382
Kev Avatar asked Oct 17 '25 10:10

Kev


1 Answers

grep uses Basic Regular Expressions, like sed and vi. In that you have to escape metacharacters, and it is tedious.

You probably want Extended Regular Expressions, so use egrep or grep -E (depending on the version in use). Check your man grep.

See also the GNU documentation for a full list of the characters involved.

Most languages use Extended Regular Expressions (EREs) these days, and they are much easier to use. Basic Regular Expressions (BREs) are really a throw-back.

like image 131
cdarke Avatar answered Oct 19 '25 08:10

cdarke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!