0

I use the regular expression to handle the string "abc123". The command below is work and return value "c123"

echo abc123 | grep -o [a-z][0-9]*$

But the command below does not work.

echo abc123 | grep -o [a-z][0-9]+$

Why do I get this result?

I knew the '*' is used to matches the preceding pattern element zero or more time, and '+' is used to matches the preceding pattern element at least one or more time.

So this situation makes me confused.

5

+ is only a quantifier in extended regular expressions (ERE):

$ echo abc123 | grep -Eo '[a-z][0-9]+$'
c123

In basic regular expressions (BRE) it matches literal +, although you can use \{1,\} instead, or in GNU grep (-o is already a GNU extension anyway), \+:

$ echo abc123 | grep -o '[a-z][0-9]\+$'
c123

(note the quotes to prevent [ and \ from being interpreted by the shell).

  • Just a comment on @StéphaneChazelas' edit: -o is a GNU extension, but it's also available in (some) other grep implementations. However, \+ in a basic regular expression is GNU-only as far as I know. – Kusalananda Dec 12 '18 at 8:15
  • @Kusalananda, I agree it's a bit of a shortcut. Several other implementations have picked some of the GNU extensions over the years. \+ is also found in some non-GNU implementations like busybox or ast-open. Also note that many BSDs still use a fork of an old GNU grep, so will support old GNU extensions like those. – Stéphane Chazelas Dec 12 '18 at 8:24
0

+ in grep need to be escaped to take effect. Instead of

echo abc123 | grep -o [a-z][0-9]+$

You need to write

echo abc123 | grep -o '[a-z][0-9]\+$'

There are other characters that need to be escaped as well. It is also good practice to put your regex in single quotes.

You can also use egrep which is a synonym of grep -E and uses Extended RE, as commented by @muru.

  • Or use ERE with -E – muru Dec 12 '18 at 4:01
  • The escaped + in basic regular expressions is a non-standard GNU extension. – Kusalananda Dec 12 '18 at 6:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.