Question about shell and grep commands

Does anyone know why

grep "p\{2\}" textfile

will find "apple" if it is in the file, but

grep p\{2\} textfile

will not be?

I am new to using the command line and regular expressions, and this puzzles me.

+3
source share
5 answers

With quotes, your full regex is passed directly to grep. Without quotes, grep sees your regular expression as p{2}.

Edit:

To clarify, without quotes, your slashes are removed by the shell before your regular expression is passed to grep.

Try:

echo grep p\{2\} test.txt

And you will see your result as ...

grep p{2} test.txt

Quotation marks prevent the shell from escaping characters before they get into grep. You can also avoid slashes and it will work without quotes -grep p\\{2\\} test.txt

0

, , :

- pid ( ps).

 PID TTY          TIME CMD

 1611 pts/0    00:00:00 su

 1619 pts/0    00:00:00 bash

 1763 pts/0    00:00:00 ps

- - strace ( tracer) pid ( 1619):

strace -f -o <output_file> -p 1619

- ,

- exec : grep

- - :

1723  execve("/bin/grep", ["grep", "--color=auto", "p{2}", "foo"], [/* 19 vars */]) = 0

1725  execve("/bin/grep", ["grep", "--color=auto", "p\\{2\\}", "foo"], [/* 19 vars */]) = 0

, grep , .:)

-e ....

+2

. "{}" , "*", .

+1

grep man

In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \).

egrep p{2} 

grep "p\{2\}" 

ERE ( ), BRE (Basic Regular Expressions) , grep ( BRE, -e), "\ {" BRE.

, 2 {p},

, grep BRE, :

grep "p\{2"

grep

grep: Unmatched \{  
0

, pp:

echo "apple" | grep 'p\{2\}'

The second one tans the template literally, then p{2}:

echo "ap {2} le" | grep p \ {2 \}
0
source

All Articles