0
$ echo 'HI' | grep '\w*'
HI
$ echo 'HI' | grep '\w+'
$ echo 'HI' | grep '\w{2}'

For cases 2 & 3, grep must have returned 'HI', but is returning nothing. Is there something wrong in what I am grepping for?

2
  • 2
    Yes, there is something wrong. Did you read the replies you received already? In grep's regex syntax, \w matches a literal w, and + matches a literal plus sign. (In this case, it's redundant anyway, because grep prints the entire input line if there is a match). You are looking for echo hi | grep -i '[a-z]' or if you really insist on using Perl's regex syntax echo hi | perl -ne 'print if /\w/' Commented Aug 30, 2011 at 10:07
  • GNU grep supports options -G (BRE: basic regular expressions), -E (ERE: extended regular expressions), -F (fixed strings, but optionally many of them), and -P (Perl regular expressions - though it doesn't say precisely which version of Perl). If you have GNU grep and want Perl-style regular expressions, use grep -P '^\w{2}$' or whatever. Commented Aug 31, 2011 at 0:16

1 Answer 1

3

Regular expressions in their pure form is precisely what Global Regular Expression Print supports. The \w escape was introduced in Perl regular expressions in the late 1980s, almost 20 years after grep was created. The GNU grep suite alludes to a command pgrep in its documentation, but you are probably better off learning the differences, and learning to use traditional regexes with grep.

Sign up to request clarification or add additional context in comments.

1 Comment

just add a -P switch to turn on PCRE (Perl Compatible Regular Expressions)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.