3

I am trying to check if a variable matches a regex in POSIX shell. However, this seems more difficult than I thought. I am trying to check if the variable is a valid size string (e.g. 10M or 6G etc)

if echo $var | grep -Eq '^\d+[MG]$';
then
    echo "match"
else
    echo "no match"
fi

That's what I tried, but for some reason I never get a match, even if the variable contains the correct string? Any idea why?

1 Answers1

7

GNU grep supports three types of regular expressions: Basic, Extended (ERE) and Perl (PCRE). In GNU grep, EREs don't provide functionality over basic ones, but some characters have special meanings, such as the plus sign. Source: man page.

\d does not mean anything special in an ERE; it's just the character d. To express digits, use [[:digit:]] or the old [0-9] (I wonder if there are character encodings where [0-9] is not the same as [[:digit:]]).

Your expression works as a PCRE, though:

if echo $var | grep -Pq '^\d+[MG]$';
then
    echo "match"
else
    echo "no match"
fi

Note the -P option instead of -E.

It would seem that POSIX grep does not support PCREs. I have not read the POSIX ERE definition, though.

berndbausch
  • 3,557