协慌网

登录 贡献 社区

如何在 Bash 中将字符串转换为小写?

有一种方法可以将字符串转换为小写字符串吗?

例如,如果我有:

a="Hi all"

我想将其转换为:

"hi all"

答案

各种方式:

POSIX 标准

TR

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

AWK

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

非 POSIX

您可能会遇到以下示例遇到的可移植性问题:

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

巴什

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

在 Bash 4 中:

小写

$ 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

大写

$ 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

切换(未记录,但可选择在编译时配置)

$ 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

大写(未记录,但可选择在编译时配置)

$ string="a few words"
$ declare -c string
$ string=$string
$ echo "$string"
A few words

标题案例:

$ 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

要关闭declare属性,请使用+ 。例如, declare +c string 。这会影响后续分配,而不会影响当前值。

declare选项更改变量的属性,但不更改内容。我的示例中的重新分配更新了内容以显示更改。

编辑:

按照ghostdog74 的建议添加 “按字首字母切换”( ${var~} )。

编辑:更正了波形符合行为以匹配 Bash 4.3。

echo "Hi All" | tr "[:upper:]" "[:lower:]"