bash中有没有将字符串转换为小写字符串的方法?
例如,如果我有:
a="Hi all"
我想将其转换为:
"hi all"
bash中有没有将字符串转换为小写字符串的方法?
例如,如果我有:
a="Hi all"
我想将其转换为:
"hi all"
当前回答
我知道这是一篇老掉牙的帖子,但我为另一个网站做了这个回答,所以我想我会把它贴在这里:
上部->下部:使用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
用于大写。
其他回答
如果使用v4,则会进行烘焙。如果不是,这里有一个简单、广泛适用的解决方案。这个线程上的其他答案(和注释)对创建下面的代码非常有用。
# Like echo, but converts to lowercase
echolcase () {
tr [:upper:] [:lower:] <<< "${*}"
}
# Takes one arg by reference (var name) and makes it lowercase
lcase () {
eval "${1}"=\'$(echo ${!1//\'/"'\''"} | tr [:upper:] [:lower:] )\'
}
笔记:
执行:a=“Hi All”,然后:lcase a将执行与:a=$相同的操作(echolcase“Hi All”)在lcase函数中,使用${!1//\'/“'\'”}而不是${!1},即使字符串有引号,也可以使用此函数。
tr:
a="$(tr [A-Z] [a-z] <<< "$a")"
AWK:
{ print tolower($0) }
sed:
y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/
我知道这是一篇老掉牙的帖子,但我为另一个网站做了这个回答,所以我想我会把它贴在这里:
上部->下部:使用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
用于大写。
你可以试试这个
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/
echo "Hi All" | tr "[:upper:]" "[:lower:]"