Home > bash > Converting strings to lowercase in bash

Converting strings to lowercase in bash

I needed to convert the values of a variable to lowercase for comparison purposes. A quick search on Google yielded some very interesting results from stackoverflow

I settled on the tr example.

string="A FEW WORDS"
$ echo $string | tr '[:upper:]' '[:lower:]'
a few words

But this just blew me away. Pity I do not have Bash 4. And no. I can’t install it on the server.

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

To uppercase

$ string="a few words"

$ echo ${string^}
A few words

$ echo ${string^^}
A FEW WORDS

$ echo ${string ^^[aeiou]}
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

Title case:

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

Please visit the stackoverflow link provided above for more examples.

Advertisements
Categories: bash Tags: , , ,
  1. Peder
    June 12, 2014 at 4:32 pm

    good work, it beats doing pipe sed ….

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: