I am trying to pattern match in my bash script but for some reason the BASH_REMATCH var is not being set with my groups.
Code below:
if [[ "SYSENV01" =~ ^(SYS)(ENV)(01)$ ]]; then
echo ${BASH_REMATCH[0]}
echo ${BASH_REMATCH[1]}
echo ${BASH_REMATCH[2]}
fi
Weirdly this prints out SYSENV01 then 2 empty lines to the command line - so it must be matching; however, the groups do not appear.
Any ideas? This has had me in circles for ages.
I agree with the commenters... it's probably a local shell issue. Here's what I get locally:
test.sh
#!/bin/bash
if [[ "SYSENV01" =~ ^(SYS)(ENV)(01)$ ]]; then
echo ${BASH_REMATCH[0]}
echo ${BASH_REMATCH[1]}
echo ${BASH_REMATCH[2]}
fi
Outputs:
~/tmp › sh ./test.sh
SYSENV01
SYS
ENV
Bash version info:
~/tmp › bash --version
GNU bash, version 3.2.51(1)-release (x86_64-apple-darwin13)
Copyright (C) 2007 Free Software Foundation, Inc.
Not as efficient, but here's the same thing using cut
:
FIRST=$(echo "SYSENV01" | cut -c1-3 )
SECOND=$(echo "SYSENV01" | cut -c4-6 )
THIRD=$(echo "SYSENV01" | cut -c7- )
echo $FIRST
echo $SECOND
echo $THIRD
Maybe you can use something like that instead?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With