0

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?

2 Answers 2

2

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}'\)'`)
Sign up to request clarification or add additional context in comments.

Comments

1

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]" )

Comments

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.