1

in a bash script, I have :

mkv="xxxx E05 xxxx"

if [[ $mkv =~ E[0-9]{2} ]] ; then echo FOUND; fi

good. this tells me if $mkv matches against E[0-9]{2}, but this is not what I want.

I want to get the matching string (i.e. 05 in my example)

I put a reference () in my regexp, hoping I'd be able to get it later, but I could not.

I tried :

if [[ $mkv =~ E([0-9]{2}) ]] ; then echo FOUND $1; fi

if [[ $mkv =~ E([0-9]{2}) ]] ; then echo FOUND \1; fi

etc... but all of them failed

thanks !

1 Answer 1

2

You can use the BASH_REMATCH array to get the parts that matched:

if [[ $mkv =~ E([0-9]{2}) ]] ; then echo FOUND ${BASH_REMATCH[1]} ; fi

${BASH_REMATCH[0]} will contain the whole/full match (Exx), ${BASH_REMATCH[1]} the first captured group (only the digits here).

Sign up to request clarification or add additional context in comments.

1 Comment

Just to add, Here REMATCH is not re-match rather regular expression match.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.