Skip to content
Advertisement

Name check match pattern

I need help as to why code B is producing a different result

x=TEST_DATA_12345678_TST_87456321

The code below (CODE A) produces the correct output (match)

if [[ $x == TEST_[A-Z][A-Z][A-Z][A-Z]_[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]_[A-Z][A-Z][A-Z]_[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9] ]]; then echo "match"; else echo "non match"; fi

However, the below (CODE B) produces a wrong output (no match)

if [[ $x == TEST_[A-Z]{4}_[0-9]{8}_[A-Z]{3}_[0-9]{8} ]]; then echo "match"; else echo "non match"; fi

Advertisement

Answer

To check a regex in an if-statement you’ll need to use =~ instead off ==;

#!/bin/bash

x=TEST_DATA_12345678_TST_87456321
if [[ $x =~ TEST_[A-Z][A-Z][A-Z][A-Z]_[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]_[A-Z][A-Z][A-Z]_[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9] ]]; then echo "match"; else echo "non match"; fi
if [[ $x =~ TEST_[A-Z]{4}_[0-9]{8}_[A-Z]{3}_[0-9]{8} ]]; then echo "match"; else echo "non match"; fi

Both will match as expected.

Try it online!

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement