How to convert a string to lower case in Bash?

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

    For Bash versions earlier than 4.0, this version should be fastest (as it doesn't fork/exec any commands):

    function string.monolithic.tolower
    {
       local __word=$1
       local __len=${#__word}
       local __char
       local __octal
       local __decimal
       local __result
    
       for (( i=0; i<__len; i++ ))
       do
          __char=${__word:$i:1}
          case "$__char" in
             [A-Z] )
                printf -v __decimal '%d' "'$__char"
                printf -v __octal '%03o' $(( $__decimal ^ 0x20 ))
                printf -v __char \\$__octal
                ;;
          esac
          __result+="$__char"
       done
       REPLY="$__result"
    }
    

    technosaurus's answer had potential too, although it did run properly for mee.

提交回复
热议问题