有没有办法进去重击bash将字符串转换为小写字符串?
例如,如果我有:
a="Hi all"
我想将其转换为:
"hi all"
有多种方式:
$ echo "$a" | tr '[:upper:]' '[:lower:]' hi all
$ echo "$a" | awk '{print tolower($0)}' hi all
您可能会遇到以下示例的可移植性问题:
$ echo "${a,,}" hi all
$ echo "$a" | sed -e 's/\(.*\)/\L\1/' hi all # this also works: $ sed -e 's/\(.*\)/\L\1/' <<< "$a" hi all
$ 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
注意:YMMV 关于这一点。即使使用shopt -u nocasematch;. 取消设置 nocasematch 会导致 [[ “fooBaR” == “FOObar” ]] 匹配正常,但奇怪的是 [bz] 与 [AZ] 不正确匹配。Bash 被双重否定(“unsetting nocasematch”)弄糊涂了!:-)
shopt -u nocasematch;