有办法进去吗bash /questions/tagged/bash将字符串转换为小写字符串?
例如,如果我有:
a="Hi all"
我想将其转换为:
"hi all"
有多种方法:
POSIX标准 https://en.m.wikipedia.org/wiki/POSIX
tr https://en.m.wikipedia.org/wiki/Tr_%28Unix%29
$ echo "$a" | tr '[:upper:]' '[:lower:]'
hi all
AWK https://en.m.wikipedia.org/wiki/AWK
$ echo "$a" | awk '{print tolower($0)}'
hi all
非 POSIX
您可能会遇到以下示例的可移植性问题:
Bash 4.0 https://en.m.wikipedia.org/wiki/Bash_%28Unix_shell%29
$ echo "${a,,}"
hi all
sed https://en.m.wikipedia.org/wiki/Sed
$ echo "$a" | sed -e 's/\(.*\)/\L\1/'
hi all
# this also works:
$ sed -e 's/\(.*\)/\L\1/' <<< "$a"
hi all
Perl https://en.m.wikipedia.org/wiki/Perl
$ echo "$a" | perl -ne 'print lc'
hi all
Bash https://en.m.wikipedia.org/wiki/Bash_%28Unix_shell%29
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
注意:YMMV 关于这一点。对我不起作用(GNU bash 版本 4.2.46 和 4.0.33(以及相同的行为 2.05b.0 但nocasematch
没有实现))即使使用shopt -u nocasematch;
。取消设置nocasematch
causes [[ "fooBaR" == "FOObar" ]]
匹配正常但里面的情况很奇怪[b-z]
被错误地匹配[A-Z]
。 Bash 被双重否定(“取消设置 nocasematch”)搞糊涂了! :-)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)