Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
433 views
in Technique[技术] by (71.8m points)

string - 如何在Bash中将字符串转换为小写?(How to convert a string to lower case in Bash?)

Is there a way in to convert a string into a lower case string?

(有一种方法可以将字符串转换为小写字符串?)

For example, if I have:

(例如,如果我有:)

a="Hi all"

I want to convert it to:

(我想将其转换为:)

"hi all"
  ask by assassin translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The are various ways:

(有多种方式:)

POSIX standard (POSIX标准)

tr (TR)

$ echo "$a" | tr '[:upper:]' '[:lower:]'
hi all

AWK (AWK)

$ echo "$a" | awk '{print tolower($0)}'
hi all

Non-POSIX (非POSIX)

You may run into portability issues with the following examples:

(您可能会遇到以下示例的可移植性问题:)

Bash 4.0 (重击4.0)

$ echo "${a,,}"
hi all

sed (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

Note: YMMV on this one.

(注意:YMMV就此。)

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;

(即使使用shopt -u nocasematch;它也对我不起作用(GNU bash版本4.2.46和4.0.33(具有相同的行为2.05b.0,但未实现nocasematch)) shopt -u nocasematch;)

.

(。)

Unsetting that nocasematch causes [[ "fooBaR" == "FOObar" ]] to match OK BUT inside case weirdly [bz] are incorrectly matched by [AZ].

(取消设置nocasematch会导致[[“” fooBaR“ ==” FOObar“]]奇怪地匹配[Bz]内的情况,但[AZ]错误地匹配了[Bz]。)

Bash is confused by the double-negative ("unsetting nocasematch")!

(Bash被双负数(“ uncasematch”)弄糊涂了!)

:-)

(:-))


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...