I have been searching to find a way to convert a string value from upper case to lower case. All the search results show approaches of using tr
command.
The problem with the tr
command is that I am able to get the result only when I use the command with echo statement. For example:
y="HELLO" echo $y| tr '[:upper:]' '[:lower:]'
The above works and results in 'hello', but I need to assign the result to a variable as below:
y="HELLO" val=$y| tr '[:upper:]' '[:lower:]' string=$val world
When assigning the value like above it gives me an empty result.
PS: My Bash version is 3.1.17
To convert a string to uppercase in Bash, use tr command. tr stands for translate or transliterate. With tr command we can translate lowercase characters, if any, in the input string to uppercase characters.
The `tr` command can be used in the following way to convert any string from uppercase to lowercase. You can use `tr` command in the following way also to convert any string from lowercase to uppercase.
The ^ operator converts to uppercase, while , converts to lowercase. If you double-up the operators, ie, ^^ or ,, , it applies to the whole string; otherwise, it applies only to the first letter (that isn't absolutely correct - see "Advanced Usage" below - but for most uses, it's an adequate description).
Java String toLowerCase() Method The toLowerCase() method converts a string to lower case letters. Note: The toUpperCase() method converts a string to upper case letters.
If you are using bash 4 you can use the following approach:
x="HELLO" echo $x # HELLO y=${x,,} echo $y # hello z=${y^^} echo $z # HELLO
Use only one ,
or ^
to make the first letter lowercase
or uppercase
.
The correct way to implement your code is
y="HELLO" val=$(echo "$y" | tr '[:upper:]' '[:lower:]') string="$val world"
This uses $(...)
notation to capture the output of the command in a variable. Note also the quotation marks around the string
variable -- you need them there to indicate that $val
and world
are a single thing to be assigned to string
.
If you have bash
4.0 or higher, a more efficient & elegant way to do it is to use bash
builtin string manipulation:
y="HELLO" string="${y,,} world"
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