My regex doesn't work in grep

Here is 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 does not print anything to stdout.

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

I am using GNU grep version 2.9.

+6
source share
4 answers

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

From human 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 energy from your regular expressions, I also recommend that you take a look at the Perl regular expression syntax. They are generally considered the most expressive. There is a C library called PCRE that mimics them, and grep links to it. To use them (instead of the basic syntax), you can use grep -P .

+6
source

You can use -E :

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

This allows extended regex. Without it, you get BREs (basic regex) that have a more simplified syntax. Alternatively, you can run egrep instead with the same result.

+2
source

I found that you need to avoid + :

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

Try grep -P '^\s+' instead if you use GNU grep. It is much easier to type on and has better regular expressions.

0
source

Source: https://habr.com/ru/post/911254/


All Articles