jhrf
jhrf

Reputation: 1000

Using a variable in a expr regex command

I am using the following bit of bash (sourced from here - I think)

bar=test_qux42_test
foo=(`expr ${bar} : '.*\(qux..\)'`)

The above returns qux42 successfully.

However, if I try the following it fails

baz=qux..
bar=test_qux42_test
foo=(`expr ${bar} : '.*\(${baz}\)'`)

I modify the command using a variable to customise the regex pattern and it fails. What am I doing wrong? How can I use a variable in the command?

Upvotes: 0

Views: 286

Answers (2)

chepner
chepner

Reputation: 532053

There's no need to use expr for regex-matching in bash, which can perform it natively:

baz=qux..
bar=test_qux42_test
[[ $bar =~ .*\($baz\) ]]
foo=( "${BASH_REMATCH[1]" )

Upvotes: 1

Andrew Clark
Andrew Clark

Reputation: 208615

Variables are not expanded inside of single quotes, try changing them to double quotes:

foo=(`expr ${bar} : ".*\(${baz}\)"`)

Or you can move the variable outside of the quotes:

foo=(`expr ${bar} : '.*\('${baz}'\)'`)

Upvotes: 2

Related Questions