1

Following statement always returns 1 when I am expecting it to return 0:

 echo "ACI123456777-001-20170701.pdf" | grep -e "^ACI([0-9]{9})-([0-9]{3})-([0-9]{8}).pdf$"
1

You observed an exit of code 1, like this:

$ echo "ACI123456777-001-20170701.pdf" | grep -e "^ACI([0-9]{9})-([0-9]{3})-([0-9]{8}).pdf$"; echo code=$?
code=1

To have it work as you expect, you need the -E` option:

$ echo "ACI123456777-001-20170701.pdf" | grep -Ee "^ACI([0-9]{9})-([0-9]{3})-([0-9]{8}).pdf$"; echo code=$?
ACI123456777-001-20170701.pdf
code=0

-E turns on extended regex features.

If you really want to use basic regex, which is the default, then you need to add several escapes:

$ echo "ACI123456777-001-20170701.pdf" | grep -e "^ACI\([0-9]\{9\}\)-\([0-9]\{3\}\)-\([0-9]\{8\}\).pdf$"; echo code=$?
ACI123456777-001-20170701.pdf
code=0

The meaning of -e

The grep option -e precedes a regex pattern:

$ echo "ACI123456777-001-20170701.pdf" | grep -e '^ACI'
ACI123456777-001-20170701.pdf

If there is only one pattern, then grep doesn't need -e and you can omit it:

$ echo "ACI123456777-001-20170701.pdf" | grep '^ACI'
ACI123456777-001-20170701.pdf

If there are two or more patterns, however, -e is needed:

$ echo "ACI123456777-001-20170701.pdf" | grep -e '^ACI' -e 'pdf'
ACI123456777-001-20170701.pdf
  • Thx. Can you please explain what does "-e" do. I did read the man description but have not understood. – AlluSingh Aug 8 '17 at 2:59
  • OK. I updated the answer with info on -e. – John1024 Aug 8 '17 at 3:05
-1
echo "ACI123456777-001-20170701.pdf"  | grep -q "ACI[0-9]\{9\}-[0-9]\{3\}-[0-9]\{8\}.pdf"
echo $?

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.