bash shell下最方便的字符串大小写转换方法

 

用tr需要新增变量,用declare或typeset需要在变量赋值前或者赋值后单独声明,都有些麻烦

此方法为bash 4.0以后新增,bash 4.0 2009年发布

$ test="abcDEF"

# 把变量中的第一个字符换成大写

$ echo ${test^}
AbcDEF

# 把变量中的所有小写字母,全部替换为大写
$ echo ${test^^}
ABCDEF

# 把变量中的第一个字符换成小写
$ echo ${test,}
abcDEF

# 把变量中的所有大写字母,全部替换为小写
$ echo ${test,,}
abcdef


https://stackoverflow.com/questions/2264428/how-to-convert-a-string-to-lower-case-in-bash

The are various ways:

POSIX standard

tr

$ echo "$a" | tr '[:upper:]' '[:lower:]'
hi all

AWK

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

Non-POSIX

You may run into portability issues with the following examples:

Bash 4.0

$ echo "${a,,}"
hi all

sed

$ echo "$a" | sed -e 's/\(.*\)/\L\1/'
hi all
# this also works:
$ sed -e 's/\(.*\)/\L\1/' <<< "$a"
hi all

Perl

$ echo "$a" | perl -ne 'print lc'
hi all

Bash

lc(){
    case "$1" in
        [A-Z])
        n=$(printf "%d" "'$1")
        n=$((n+32))
        printf \\$(printf "%o" "$n")
        ;;
        *)
        printf "%s" "$1"
        ;;
    esac
}
word="I Love Bash"
for((i=0;i<${#word};i++))
do
    ch="${word:$i:1}"
    lc "$ch"
done
 
 
posted @ 2023-04-22 21:45  牧之丨  阅读(132)  评论(0编辑  收藏  举报