如何在 Bash 中将字符串转换为小写? [英] How to convert a string to lower case in Bash?

查看:31
本文介绍了如何在 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/(.*)/L1/'
hi all
# this also works:
$ sed -e 's/(.*)/L1/' <<< "$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.对我不起作用(GNU bash 版本 4.2.46 和 4.0.33(和相同的行为 2.05b.0 但没有实现 nocasematch)),即使使用 shopt -u nocasematch;.取消设置 nocasematch 导致 [[ "fooBaR" == "FOObar" ]] 匹配 OK 但内部情况很奇怪 [b-z] 被 [A-Z] 错误匹配.Bash 被双重否定(unsetting nocasematch")弄糊涂了!:-)

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆