How to convert a string to lower case in Bash?

前端 未结 20 2047
慢半拍i
慢半拍i 2020-11-22 09:40

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:<

20条回答
  •  太阳男子
    2020-11-22 10:10

    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, but optionally configurable at compile time)

    $ 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, but optionally configurable at compile time)

    $ 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
    
    $ string="a FeW WOrdS"
    $ string=${string,,}
    $ string=${string~}
    $ 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.

    The declare options change the attribute of the variable, but not the contents. The reassignments in my examples update the contents to show the changes.

    Edit:

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

    Edit: Corrected tilde behavior to match Bash 4.3.

提交回复
热议问题