Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string and pick the uppercase substring

Consider the following example variables in bash:

PET="cat/DOG/hamster"

FOOD="soup/soup/PIZZA"

SUBJECT="MATH/physics/biology"

How can I split any of those strings by a slash, extract the part that's all uppercase and store it in a variable? For example, how would I take DOG out of the $PET variable and store it in an $OPTION variable?

I need a portable solution that works under bash and zsh specifically.

like image 927
fabiomaia Avatar asked Sep 11 '26 10:09

fabiomaia


1 Answers

You could use tr to remove all characters that are not uppercase:

OPTION=$(tr -dc '[:upper:]' <<< $PET)

Note that here-strings (<<< $VARIABLE) are a bash-ism. In other shells you'll have to echo the variable into tr:

OPTION=$(echo "$PET" | tr -dc '[:upper:]')
like image 144
Ansgar Wiechers Avatar answered Sep 13 '26 23:09

Ansgar Wiechers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!