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

47 浏览
0 Comments

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

在<bash中是否有一种方法将字符串转换为小写字符串?

例如,如果我有:

a="Hi all"

我想将其转换为:

"hi all"

admin 更改状态以发布 2023年5月23日
0
0 Comments

在 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。

0
0 Comments

有不同的方式:

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

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

注意:对此可能会有不同的经验。即使使用shopt -u nocasematch;也不能为我(GNU bash版本4.2.46和4.0.33(相同的行为2.05b.0但未实现nocasematch))工作。取消nocasematch会导致[[ "fooBaR" == "FOObar" ]]匹配成功,但在case语句中,[b-z]会被错误地匹配为[A-Z]。Bash被双重否定(“取消nocasematch”)搞混了!:-)

0