I am looking for BASH regex to pull the 'db' agruments from the below commands. The order of the arguments is not guaranteed however. For some reason I cannot get it to work completely.
What I have so far
regex="--db (.*)($| --)"
[[ $@ =~ $regex ]]
DB_NAMES="${BASH_REMATCH[1]}"
# These are example lines
somecommand --db myDB --conf /var/home # should get "myDB"
somecommand --db myDB anotherDB manymoreDB --conf /home # should get "myDB anotherDB manymoreDB"
somecommand --db myDB # should get "myDB"
somecommand --db myDB anotherDB # should get "myDB anotherDB"
Any suggestion on the regex?
The problem is that bash
uses a flavor of regex
that does not include non-greedy repetition operators (*?
, +?
). Because *
is greedy and there is no way to tell it to not be greedy, the first parenthesized subexpression ((.*)
) matches everything up to the end of line.
You can work around this if you know for that the values you want to capture do not contain a certain character and replace .
with the character class that excludes that character.
For example, if the values after --db
do not contain dashes (-
) you can use this regex
:
regex='--db ([^-]*)($| --)'
It matches all the examples posted in the question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With