如何在 Bash 中将大写转换为小写或相反?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9371416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I convert uppercase to lowercase or the other way around in Bash?
提问by cacosud
Possible Duplicate:
converting string to lower case in bash shell scripting
For example:
例如:
echo *****Language translator*****
echo please choose the language
for Chinese enter c
for French enter f
In a simple way I want to be able to recognize both C and c for Chinese; and the same thing for f and F, recognized as French.
以一种简单的方式,我希望能够识别中文的 C 和 c;和 f 和 F 相同,被认为是法语。
Is there a way to convert everything to lower case?
有没有办法将所有内容都转换为小写?
Here part of the code:
这里部分代码:
if [ $language == c ];
then
echo "Enter the word to translate:"
read word_to_translate
如果 [ $language == c ];
然后
回显“输入要翻译的单词:”
阅读 word_to_translate
回答by Mike Bockus
You can use trto switch the chars to lowercase/uppercase:
您可以使用tr将字符切换为小写/大写:
echo $language | tr '[A-Z]' '[a-z]'
回答by Adam Liss
You can use the following case-modifiers (from man bash):
您可以使用以下大小写修饰符(来自man bash):
${parameter^} # Convert the first character in ${parameter} to uppercase
${parameter^^} # Convert all characters in ${parameter} to uppercase
${parameter,} # Convert the first character in ${parameter} to lowercase
${parameter,,} # Convert all characters in ${parameter} to lowercase
So your code might look something like this:
所以你的代码可能看起来像这样:
# Read one character into $lang, with a nice prompt.
read -n 1 -p "Please enter c for Chinese, or f for French: " lang
if [ "${lang,,}" == "c" ]; then
echo "Chinese"
elif [ "${lang,,}" == "f" ]; then
echo "French"
else
echo "I don't speak that language."
fi
回答by jim mcnamara
Modern versions of tr have support for POSIX character classes [:upper:] and [:lower:]
tr 的现代版本支持 POSIX 字符类 [:upper:] 和 [:lower:]
tr -s '[:upper:]' '[:lower:]' < inputfile > outputfile
All of the character classes are here:
所有的字符类都在这里:
http://ss64.com/bash/tr.html
回答by Jonathan Leffler
I'd probably use a case statement, though there are other ways to do it:
我可能会使用 case 语句,但还有其他方法可以做到:
read language
case "$language" in
([cC]) echo 'Chinese';;
([fF]) echo 'French';;
(*) echo 'Unrecognized language abbreviation';;
esac
You could make a canonical assignment in the caseif you need the values outside the switch:
case如果您需要开关之外的值,您可以在中进行规范分配:
read language
case "$language" in
([cC]) lingua='zh_tw'; echo 'Chinese';;
([fF]) lingua='fr_fr'; echo 'French';;
(*) echo 'Unrecognized language abbreviation';;
esac

