0

Im trying to search for a pattern in a file as follows:

SRC_ERROR_CODE=105
SRC_ERROR_CODE=106
...

To achieve this following is the grep statement used:

grep -io "[a-z]*_error_code=[0-9]*" events.log

However i was wondering if instead of using the "*" which fetches 0 to n occurrences of the preceding matched character, the "+" should fetch the same results as well as below:

grep -io "[a-z]+_error_code=[0-9]+" events.log

But, this doesn't seem to work. Could you please guide as to why it doesn't.

Thanks

1
  • Im not sure what your question is. + will select 1 to N occurrences, and unless specified is greedy in terms of finding matches. I think you need to give more information. Why doesnt it work? Is it returning the wrong set, or is it returning an error, or what? Commented Dec 21, 2015 at 2:18

2 Answers 2

2

In POSIX Basic Regular Expressions (BRE), the default regex dialect used by grep, + just matches itself.

In POSIX Extended Regular Expressions (ERE) and Perl Compatible RegEx (PCRE), + matches 1 or more of the preceding atom.

You can ask grep to use ERE with the -E option:

$ echo "foo baaar" | grep -o -E 'a+'
aaa
Sign up to request clarification or add additional context in comments.

Comments

0

The + in regex matches one or more character in Extended Regular Expression (ERE - this is egrep)

In Basic regular expression (BRE) you have to escape the + sign.

Since you are using grep, you have to escape the +. Therefore, use \+ instead of +.

If you are using egrep, you can use the unescaped +

1 Comment

These days, egrep is just an (effective) alias for grep -E (similarly, fgrep maps onto grep -F). For long-term POSIX compliance it's better to use grep with options. While both BSD grep and GNU grep do support \+ in BREs, it's important to note that \+ in BREs is not POSIX-compliant and other tools, such as sed on BSD-like platforms, do not support it; the POSIX-compliant equivalent of the + ERE construct is the - somewhat cumbersome - \{1,\}.

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.