Friday, April 26, 2024
 Popular · Latest · Hot · Upcoming
65
rated 0 times [  65] [ 0]  / answers: 1 / hits: 102283  / 2 Years ago, thu, august 25, 2022, 4:39:24

What is the Bash command I can use to convert an upper-case string to lower-case and vice-versa?



Thank you.


More From » bash

 Answers
4

If the string is already stored in a variable you can use bash's parameter expansion, specifially ${parameter,,pattern} (available since bash 4.0), where parameter is the name of your variable and pattern is ommitted:



$ string="Hello, World!"
$ echo $string
Hello, World!
$ echo ${string,,}
hello, world!


Note that this does not change the value of the variable, only the output. To change the variable you have to assign the new value:



$ echo $string
Hello, World!
$ string=${string,,}
$ echo $string
hello, world!


The upper-case conversion works with ${parameter^^pattern}:



$ echo ${string^^}
HELLO, WORLD!


This works also with Unicode strings (at least with current bash versions, probably needs at least bash 4.3):



$ string='ἈΛΦΆβητος'
$ echo ${string,,}
ἀλφάβητος
$ echo ${string^^}
ἈΛΦΆΒΗΤΟΣ





If you are using zsh, you can use Parameter Expansion Flags (${(FLAGS)NAME}; available since zsh 2.5) to achieve the same results. The bash syntax does not work in zsh 1). The flag for lower case is L; for upper case it is U:



$ string="Hello, World!"
$ echo ${(L)string}
hello, world!
$ echo ${(U)string}
HELLO, WORLD!
$ echo $string
Hello, World!"


This also works with Unicode strings (at least since zsh 5.0; I did not try with earlier versions):



$ string='ἈΛΦΆβητος'
$ echo ${(L)string}
ἀλφάβητος
$ echo ${(U)string}
ἈΛΦΆΒΗΤΟΣ






1) Although, seeing that zsh had this for far longer, it should probably be: "the zsh syntax does not work in bash.


[#28211] Friday, August 26, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ainbby

Total Points: 184
Total Questions: 115
Total Answers: 112

Location: Colombia
Member since Thu, Sep 29, 2022
2 Years ago
ainbby questions
Thu, Mar 23, 23, 10:26, 1 Year ago
Wed, May 10, 23, 00:10, 1 Year ago
Fri, Apr 15, 22, 10:11, 2 Years ago
;