Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash regular expression groups not working

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.

like image 833
user2294382 Avatar asked Dec 13 '13 17:12

user2294382


1 Answers

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?

like image 159
Donovan Avatar answered Sep 29 '22 22:09

Donovan