Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string to lower case in Bash?

Is there a way in bash to convert a string into a lower case string?

For example, if I have:

a="Hi all" 

I want to convert it to:

"hi all" 
like image 436
assassin Avatar asked Feb 15 '10 07:02

assassin


People also ask

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.

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 you change to lowercase in Linux?

You can change the case of the string very easily by using tr command. To define uppercase, you can use [:upper:] or [A-Z] and to define lowercase you can define [:lower:] or [a-z]. The `tr` command can be used in the following way to convert any string from uppercase to lowercase.

How do I convert a variable to lowercase in shell script?

Use the tr command to convert all incoming text / words / variable data from upper to lower case or vise versa (translate all uppercase characters to lowercase). Bash version 4. x+ user can use parameter expansion to modify the case of alphabetic characters in parameter.


1 Answers

The are various ways:

POSIX standard

tr

$ echo "$a" | tr '[:upper:]' '[:lower:]' hi all 

AWK

$ echo "$a" | awk '{print tolower($0)}' hi all 

Non-POSIX

You may run into portability issues with the following examples:

Bash 4.0

$ echo "${a,,}" hi all 

sed

$ echo "$a" | sed -e 's/\(.*\)/\L\1/' hi all # this also works: $ sed -e 's/\(.*\)/\L\1/' <<< "$a" hi all 

Perl

$ echo "$a" | perl -ne 'print lc' hi all 

Bash

lc(){     case "$1" in         [A-Z])         n=$(printf "%d" "'$1")         n=$((n+32))         printf \\$(printf "%o" "$n")         ;;         *)         printf "%s" "$1"         ;;     esac } word="I Love Bash" for((i=0;i<${#word};i++)) do     ch="${word:$i:1}"     lc "$ch" done 

Note: YMMV on this one. Doesn't work for me (GNU bash version 4.2.46 and 4.0.33 (and same behaviour 2.05b.0 but nocasematch is not implemented)) even with using shopt -u nocasematch;. Unsetting that nocasematch causes [[ "fooBaR" == "FOObar" ]] to match OK BUT inside case weirdly [b-z] are incorrectly matched by [A-Z]. Bash is confused by the double-negative ("unsetting nocasematch")! :-)

like image 128
ghostdog74 Avatar answered Sep 18 '22 11:09

ghostdog74