Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My regular expression isn't working in grep

Tags:

linux

grep

unix

Here's the text of the file I'm working with:

(4 spaces)Hi, everyone

(1 tab)yes

When I run this command - grep '^[[:space:]]+' myfile - it doesn't print anything to stdout.

Why doesn't it match the whitespace in the file?

I'm using GNU grep version 2.9.

like image 820
thlgood Avatar asked Mar 21 '12 00:03

thlgood


3 Answers

There are several different regular expression syntaxes. The default for grep is called basic syntax in the grep documentation.

From man grep(1):

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

Therefore instead of + you should have typed \+:

grep '^[[:space:]]\+' FILE

If you need more power from your regular expressions, I also encourage you to take a look at Perl regular expression syntax. They are generally considered the most expressive. There is a C library called PCRE which emulates them, and grep links to it. To use them (instead of basic syntax) you can use grep -P.

like image 72
Andrew Tomazos Avatar answered Nov 01 '22 10:11

Andrew Tomazos


You could use -E:

grep -E '^[[:space:]]+' FILE

This enables extended regex. Without it you get BREs (basic regex) which have a more simplified syntax. Alternatively you could run egrep instead with the same result.

like image 20
FatalError Avatar answered Nov 01 '22 09:11

FatalError


I found you need to escape the +:

grep '^[[:space:]]\+' FILE
like image 29
Adam Avatar answered Nov 01 '22 10:11

Adam