如何在Bash中将字符串转换为小写? [英] How to convert a string to lower case in Bash?
问题描述
bash 的方法中是否有一种方法可以转换字符串变成小写字符串?
Is there a way in bash to convert a string into a lower case string?
例如,如果我有:
a="Hi all"
我想将其转换为:
"hi all"
推荐答案
有多种方法:
$ echo "$a" | tr '[:upper:]' '[:lower:]'
hi all
AWK
$ echo "$a" | awk '{print tolower($0)}'
hi all
非POSIX
您可能会遇到以下示例的可移植性问题:
Non-POSIX
You may run into portability issues with the following examples:
$ 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
注意:YMMV在这一点上.即使使用shopt -u nocasematch;
,它也对我不起作用(GNU bash版本4.2.46和4.0.33(具有相同的行为2.05b.0,但未实现大小写匹配)).取消设置nocasematch会导致[[-"fooBaR" =="FOObar"]]奇怪地匹配[B-z]内的情况,但[A-Z]不正确地匹配了[b-z]. Bash被双重负数("uncasematch")弄糊涂了! :-)
Note: YMMV on this one. Doesn't work for me (GNU bash version 4.2.46 and 4.0.33 (and same behaviour 2.05b.0 but nocasematch is not implemented)) even with using shopt -u nocasematch;
. Unsetting that nocasematch causes [[ "fooBaR" == "FOObar" ]] to match OK BUT inside case weirdly [b-z] are incorrectly matched by [A-Z]. Bash is confused by the double-negative ("unsetting nocasematch")! :-)
这篇关于如何在Bash中将字符串转换为小写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!