As I had mentioned in the comments, there is a shell expansion to do this: ${variable^^}
will transform the text into variable
high-cash.
I’ll copy the examples of this answer in Stackoverflow international, because it even shows behaviors that I didn’t know:
$ string="a few words"
$ echo "${string^}"
A few words
$ echo "${string^^}"
A FEW WORDS
$ echo "${string^^[aeiou]}"
A fEw wOrds
$ string="A Few Words"
$ declare -u string
$ string=$string; echo "$string"
A FEW WORDS
- expansion with a single circumflex
${var^}
transforms the first letter cashier
- expansion with two circumflex
${var^^}
transforms all letters cashier
- expansion with an expression blob after the circumflex transforms the characters that match the pattern
On this default expression, note that if you use it with a single circumflex, it will only put it in a high box if the first character matches the expression:
$ var=abcd
$ echo ${var^[bcd]}
abcd
$ echo ${var^^[bcd]}
aBCD
$ echo ${var^[abcd]}
Abcd
You can understand expansion with circumflex a special case of expansion with circumflex + pattern:
$ echo ${var^^?}
ABCD
$ echo ${var^?}
Abcd
The advantage of this alternative to using awk
, tr
, perl
is that you do not start a new process, the whole execution is done "directly" by Bash.
To turn into lowercase, the expansion uses commas instead of the circumflex. Everything else behaves similarly:
$ string="A FEW WORDS"
$ echo "${string,}"
a FEW WORDS
$ echo "${string,,}"
a few words
$ echo "${string,,[aeiou]}"
a FeW WoRDS
$ string="A Few Words"
$ declare -l string
$ string=$string; echo "$string"
a few words
Out of curiosity, did you notice that there is a special variable statement that turns it into a high box or low box in the simple assignment? This is done through the declare
of the variable.
In the answer from where I got the examples I found nothing that referenced the why of the pattern of the arguments of declare
, but I found this to be extremely noteworthy:
The declare options change the attribute of the variable, but not the Contents. The reassignments in my examples update the Contents to show the changes.
In free translation:
The options of declare
change the variable attribute, but not its content. Re-allocations in the examples update the content to show changes.
So why use -u
for high cash and -l
for low box? If you think in English, it is easier to remember:
- drop box, lowercase,
-l
- high box, uppercase,
-u
Then stay these mnemonics to help in the memorization of flags of variable declaration.
https://stackoverflow.com/questions/2264428/how-to-convert-a-string-to-lower-case-in-bash
– Costamilam