0

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
user2008558
  • 341
  • 5
  • 16

1 Answers1

1

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!

0stone0
  • 34,288
  • 4
  • 39
  • 64
  • 1
    Note that glob matches (with `=` or `==`) must match the entire string; by default, regex matches only need to match *part of* the string. To force whole-string matching, add anchors: `^` at the beginning, and `$` at the end. – Gordon Davisson Feb 09 '21 at 19:31