0

I have a Regex that I got to work in a sed search/replace line, but I can't get the Regex to work in an If-Then-Else. This is my sed line:

YELLOW="\033[1;33m"
OUTPUT[0]="$YELLOW ==================================+==================================="
cLEN=${OUTPUT[0]}
cLEN="$(echo $cLEN | sed 's/\\[[:digit:]]\+\[[[:digit:]];[[:digit:]]\+m//g')"

However now I am trying to make an if condition and I can't get the syntax right. I need it to evaluate from the beginning of the line $cLEN

if [[ $cLEN  =~ '^\\[[:digit:]]\+\[[[:digit:]];[[:digit:]]\+m\s' ]]; then
        echo true
    else
        echo error
        exit 1
fi
VLAZ
  • 26,331
  • 9
  • 49
  • 67
WesZ
  • 41
  • 4
  • You can't quote the right-hand side if you want it to be treated as a regex. – Charles Duffy Oct 26 '18 at 16:50
  • Also, `\s` isn't guaranteed to work (it's a PCRE extension not part of the ERE standard, so whether it's valid in `=~` depends on your local standard C library's regex parser). Use `[[:space:]]` instead. – Charles Duffy Oct 26 '18 at 16:52
  • Also, the `\+` doesn't need to be escaped in ERE (the regex variant used in `=~`) like it does in BRE (the regex variant used by `sed` without `-r` or `-E`); it can just be `+`. – Charles Duffy Oct 26 '18 at 16:53

1 Answers1

0

When the right-hand side of =~ is quoted, it's treated as a literal string to match, not a regex.

Store your regex in a variable, then leave the reference to that variable unquoted on the right-hand side of the expression.

re='^\\[[:digit:]]+\[[[:digit:]];[[:digit:]]+m'
[[ $cLEN =~ $re ]]; echo $?
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441