Shay Guy
Shay Guy

Reputation: 1060

How can I extract specific parts of a string matching a specific regex in bash?

I'm working in bash, chosen mainly so I could get some practice with it, and I have a string that I know matches the regex [:blank:]+([0-9]+)[:blank:]+([0-9]+)[:blank:]+$SOMETHING, assuming I got that right. (Whitespace, digits, whitespace, digits, whitespace, some string I've previously defined.) By "matches," I mean it includes this format as a substring.

Is there a way to set the two strings of digits to specific variables with just one regex matching?

Upvotes: 0

Views: 174

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799520

$BASH_REMATCH contains the groups from the latest regex comparison done by [[.

$ [[ ' 123 456 ' =~ [[:blank:]]+([0-9]+)[[:blank:]]+([0-9]+)[[:blank:]]+ ]] && echo "*${BASH_REMATCH[1]}*${BASH_REMATCH[2]}*"
*123*456*

Upvotes: 1

Related Questions