Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining regular expressions in bash script

Tags:

regex

bash

I am trying to compare a string with the $ character, followed by either s or t and a range of numbers. but the range is different for each letter. for example if it is an s it can be followed by numbers between 0-7 and if it is a t it can be followed by numbers between 0-9.

What I managed to write a part of the if statement to compare it, but I couldn't figure out how to include different ranges for each letter

script:

#!/bin/bash
input="test1.txt"
check(){
    while read -r line; do
      a=( $line )
      for i in "${a[@]:1}"; do
         if [[ "$i" == \$[st]* ]]; then
             echo "$i"
         fi
      done
    done < "$input"
}
check

Instead of using * I want to specify for s that it can only be followed by numbers between 0-7 and t can only be followed by numbers 0-9. I tried using this:

if [[ "$i" == \$(s[0-7]*|t[0-9]*) ]]; then

but I got this error:

./test.sh: line 9: syntax error in conditional expression: unexpected token `('                                         ./test.sh: line 9: syntax error near `\$(s'                                                                             ./test.sh: line 9: `if [[ "$i" == \$(s[0-7]*|t[0-9]*) ]]; then'  
like image 503
David Avatar asked Dec 09 '25 09:12

David


1 Answers

=~ is used for regex matching, not ==. Correct that and use a pipe (|) in your regex, which means OR.

if [[ $i =~ \$(s[0-7]*|t[0-9]*) ]]
like image 57
oguz ismail Avatar answered Dec 10 '25 23:12

oguz ismail



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!