How to convert a string to lower case in Bash?

前端 未结 20 2016
慢半拍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:06

    I know this is an oldish post but I made this answer for another site so I thought I'd post it up here:

    UPPER -> lower: use python:

    b=`echo "print '$a'.lower()" | python`
    

    Or Ruby:

    b=`echo "print '$a'.downcase" | ruby`
    

    Or Perl (probably my favorite):

    b=`perl -e "print lc('$a');"`
    

    Or PHP:

    b=`php -r "print strtolower('$a');"`
    

    Or Awk:

    b=`echo "$a" | awk '{ print tolower($1) }'`
    

    Or Sed:

    b=`echo "$a" | sed 's/./\L&/g'`
    

    Or Bash 4:

    b=${a,,}
    

    Or NodeJS if you have it (and are a bit nuts...):

    b=`echo "console.log('$a'.toLowerCase());" | node`
    

    You could also use dd (but I wouldn't!):

    b=`echo "$a" | dd  conv=lcase 2> /dev/null`
    

    lower -> UPPER:

    use python:

    b=`echo "print '$a'.upper()" | python`
    

    Or Ruby:

    b=`echo "print '$a'.upcase" | ruby`
    

    Or Perl (probably my favorite):

    b=`perl -e "print uc('$a');"`
    

    Or PHP:

    b=`php -r "print strtoupper('$a');"`
    

    Or Awk:

    b=`echo "$a" | awk '{ print toupper($1) }'`
    

    Or Sed:

    b=`echo "$a" | sed 's/./\U&/g'`
    

    Or Bash 4:

    b=${a^^}
    

    Or NodeJS if you have it (and are a bit nuts...):

    b=`echo "console.log('$a'.toUpperCase());" | node`
    

    You could also use dd (but I wouldn't!):

    b=`echo "$a" | dd  conv=ucase 2> /dev/null`
    

    Also when you say 'shell' I'm assuming you mean bash but if you can use zsh it's as easy as

    b=$a:l
    

    for lower case and

    b=$a:u
    

    for upper case.

提交回复
热议问题