bash中有没有将字符串转换为小写字符串的方法?

例如,如果我有:

a="Hi all"

我想将其转换为:

"hi all"

当前回答

预冲击4.0

Bash降低字符串的大小写并赋值给变量

VARIABLE=$(echo "$VARIABLE" | tr '[:upper:]' '[:lower:]') 

echo "$VARIABLE"

其他回答

基于Dejay Clayton出色的解决方案,我将大写/小写扩展为转置函数(独立有用),在变量中返回结果(更快/更安全),并添加了BASH v4+优化:

pkg::transpose() { # <retvar> <string> <from> <to>
  local __r=$2 __m __p
  while [[ ${__r} =~ ([$3]) ]]; do
    __m="${BASH_REMATCH[1]}"; __p="${3%${__m}*}"
    __r="${__r//${__m}/${4:${#__p}:1}}"
  done
  printf -v "$1" "%s" "${__r}"
}
pkg::lowercase() { # <retvar> <string>
  if (( BASH_VERSINFO[0] >= 4 )); then
    printf -v "$1" "%s" "${2,,}"
  else
    pkg::transpose "$1" "$2" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" \
                   "abcdefghijklmnopqrstuvwxyz"
  fi
}
pkg::uppercase() { # <retvar> <string>
  if (( BASH_VERSINFO[0] >= 4 )); then
    printf -v "$1" "%s" "${2^^}"
  else
    pkg::transpose "$1" "$2" "abcdefghijklmnopqrstuvwxyz" \
                   "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  fi
}

为了简单起见,我没有添加任何set-e支持(或任何错误检查)。。。但除此之外,它通常遵循shellguide和pkg::transpose()试图避免printf-v的任何可能的变量名冲突

我知道这是一篇老掉牙的帖子,但我为另一个网站做了这个回答,所以我想我会把它贴在这里:

上部->下部:使用python:

b=`echo "print '$a'.lower()" | python`

或Ruby:

b=`echo "print '$a'.downcase" | ruby`

或Perl:

b=`perl -e "print lc('$a');"`

或PHP:

b=`php -r "print strtolower('$a');"`

或者Awk:

b=`echo "$a" | awk '{ print tolower($1) }'`

或Sed:

b=`echo "$a" | sed 's/./\L&/g'`

或Bash 4:

b=${a,,}

或NodeJS:

b=`node -p "\"$a\".toLowerCase()"`

您也可以使用dd:

b=`echo "$a" | dd  conv=lcase 2> /dev/null`

下部->上部:

使用python:

b=`echo "print '$a'.upper()" | python`

或Ruby:

b=`echo "print '$a'.upcase" | ruby`

或Perl:

b=`perl -e "print uc('$a');"`

或PHP:

b=`php -r "print strtoupper('$a');"`

或者Awk:

b=`echo "$a" | awk '{ print toupper($1) }'`

或Sed:

b=`echo "$a" | sed 's/./\U&/g'`

或Bash 4:

b=${a^^}

或NodeJS:

b=`node -p "\"$a\".toUpperCase()"`

您也可以使用dd:

b=`echo "$a" | dd  conv=ucase 2> /dev/null`

另外,当你说“shell”时,我假设你是指bash,但如果你能使用zsh,那就很简单了

b=$a:l

对于小写和

b=$a:u

用于大写。

许多答案使用外部程序,而不是真正使用Bash。

如果你知道你将有Bash4可用,你真的应该使用${VAR,,}符号(这很简单,很酷)。对于Bash before 4(例如,我的Mac仍然使用Bash 3.2)。我使用@ghostdog74的答案的修正版本创建了一个更便携的版本。

一个可以称为小写的“我的字符串”并获得小写版本。我阅读了关于将结果设置为var的评论,但这在Bash中不是真正可移植的,因为我们不能返回字符串。打印它是最好的解决方案。使用类似于var=“$(小写$str)”的内容很容易捕获。

这是如何工作的

其工作方式是通过printf获取每个字符的ASCII整数表示,然后如果上到->下加32,或者如果下到->上减32。然后再次使用printf将数字转换回字符。从“A”到->“A”,我们有32个字符的差异。

使用printf解释:

$ printf "%d\n" "'a"
97
$ printf "%d\n" "'A"
65

97 - 65 = 32

这是带有示例的工作版本。请注意代码中的注释,因为它们解释了很多内容:

#!/bin/bash

# lowerupper.sh

# Prints the lowercase version of a char
lowercaseChar(){
    case "$1" in
        [A-Z])
            n=$(printf "%d" "'$1")
            n=$((n+32))
            printf \\$(printf "%o" "$n")
            ;;
        *)
            printf "%s" "$1"
            ;;
    esac
}

# Prints the lowercase version of a sequence of strings
lowercase() {
    word="$@"
    for((i=0;i<${#word};i++)); do
        ch="${word:$i:1}"
        lowercaseChar "$ch"
    done
}

# Prints the uppercase version of a char
uppercaseChar(){
    case "$1" in
        [a-z])
            n=$(printf "%d" "'$1")
            n=$((n-32))
            printf \\$(printf "%o" "$n")
            ;;
        *)
            printf "%s" "$1"
            ;;
    esac
}

# Prints the uppercase version of a sequence of strings
uppercase() {
    word="$@"
    for((i=0;i<${#word};i++)); do
        ch="${word:$i:1}"
        uppercaseChar "$ch"
    done
}

# The functions will not add a new line, so use echo or
# append it if you want a new line after printing

# Printing stuff directly
lowercase "I AM the Walrus!"$'\n'
uppercase "I AM the Walrus!"$'\n'

echo "----------"

# Printing a var
str="A StRing WITH mixed sTUFF!"
lowercase "$str"$'\n'
uppercase "$str"$'\n'

echo "----------"

# Not quoting the var should also work, 
# since we use "$@" inside the functions
lowercase $str$'\n'
uppercase $str$'\n'

echo "----------"

# Assigning to a var
myLowerVar="$(lowercase $str)"
myUpperVar="$(uppercase $str)"
echo "myLowerVar: $myLowerVar"
echo "myUpperVar: $myUpperVar"

echo "----------"

# You can even do stuff like
if [[ 'option 2' = "$(lowercase 'OPTION 2')" ]]; then
    echo "Fine! All the same!"
else
    echo "Ops! Not the same!"
fi

exit 0

运行此操作后的结果:

$ ./lowerupper.sh 
i am the walrus!
I AM THE WALRUS!
----------
a string with mixed stuff!
A STRING WITH MIXED STUFF!
----------
a string with mixed stuff!
A STRING WITH MIXED STUFF!
----------
myLowerVar: a string with mixed stuff!
myUpperVar: A STRING WITH MIXED STUFF!
----------
Fine! All the same!

不过,这只适用于ASCII字符。

对我来说,这很好,因为我知道我只会向它传递ASCII字符。例如,我在某些不区分大小写的CLI选项中使用此选项。

你可以试试这个

s="Hello World!" 

echo $s  # Hello World!

a=${s,,}
echo $a  # hello world!

b=${s^^}
echo $b  # HELLO WORLD!

裁判:http://wiki.workassis.com/shell-script-convert-text-to-lowercase-and-uppercase/

Bash 5.1提供了一种通过L参数转换实现这一点的直接方法:

${var@L}

例如,你可以说:

v="heLLo"
echo "${v@L}"
# hello

也可以使用U大写:

v="hello"
echo "${v@U}"
# HELLO

第一个字母用u大写:

v="hello"
echo "${v@u}"
# Hello