Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string from uppercase to lowercase in Bash? [duplicate]

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

like image 991
raga Avatar asked Jul 09 '12 09:07

raga


People also ask

How do you change uppercase to lowercase in bash?

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.

How do I change capitals to lowercase in Linux?

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.

How do you make a lowercase in shell script?

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).

How do I convert a string to lowercase?

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.


2 Answers

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.

like image 117
kev Avatar answered Sep 17 '22 15:09

kev


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" 
like image 23
Rody Oldenhuis Avatar answered Sep 17 '22 15:09

Rody Oldenhuis