views:

5103

answers:

5

Hi, Is there a way in bash shell scripting so that I can convert a string into lower case string. For example,

if $a = "Hi all"

I want to convert it to

$a = "hi all"

Thanks a lot for your help

+5  A: 

tr:

a="$(tr [A-Z] [a-z] <<< "$a")"

awk:

{ print tolower($0) }

sed:

y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/
Ignacio Vazquez-Abrams
+7  A: 
echo "Hi All" | tr "[:upper:]" "[:lower:]"
shuvalov
+23  A: 

various ways

tr

$ echo $a | tr '[A-Z]' '[a-z]'
hi all

awk

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

bash 4.0

$ echo ${a,,}
hi all

Perl

$ echo $a|perl -e 'print lc <>;'
hi all

Bash

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

In Bash 4:

To lowercase

$ string="A FEW WORDS"
$ echo ${string,}
a FEW WORDS
$ echo ${string,,}
a few words
$ echo ${string,,[AEIUO]}
a FeW WoRDS

$ string="A Few Words"
$ declare -l string
$ string=$string; echo $string
a few words

To uppercase

$ 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

Toggle (undocumented)

$ string="A Few Words"
$ echo ${string~~}
a fEW wORDS
$ string="A FEW WORDS"
$ echo ${string~}
a fEW wORDS
$ string="a few words"
$ echo ${string~}
A Few Words

Capitalize (undocumented)

$ string="a few words"
$ declare -c string
$ string=$string
$ echo $string
A few words

Title case:

$ string="a few words"
$ string=($string)
$ string=${string[@]^}
$ echo $string
A Few Words

$ declare -c string
$ string=(a few words)
$ echo ${string[@]}
A Few Words

To turn off a declare attribute, use "+". For example, declare +c string. This affects subsequent assignments and not the current value.

Edit:

Added "toggle first character by word" (${var~}) as suggested by ghostdog74.

Dennis Williamson
there's also `${string~}`
ghostdog74
A: 

woaw !!! So many possibilities... and so little time.

thanks dude.

Romain