可能重复:
converting string to lower case in bash shell scripting
例如:
echo *****Language translator*****
echo please choose the language
for Chinese enter c
for French enter f
以简单的方式,我希望能够识别中文的C和c; 和F和F一样,被认为是法国人。
有没有办法将所有内容转换为小写?
这部分代码:
如果[$ language == c];
然后
echo“输入要翻译的单词:”
阅读word_to_translate
答案 0 :(得分:7)
您可以使用tr
将字符切换为小写/大写:
echo $language | tr '[A-Z]' '[a-z]'
答案 1 :(得分:3)
您可以使用以下案例修饰符(来自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
所以你的代码看起来像这样:
# 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
答案 2 :(得分:2)
现代版本的tr支持POSIX字符类[:upper:]和[:lower:]
tr -s '[:upper:]' '[:lower:]' < inputfile > outputfile
所有角色类都在这里:
http://ss64.com/bash/tr.html
答案 3 :(得分:2)
我可能会使用案例陈述,但还有其他方法可以做到:
read language
case "$language" in
([cC]) echo 'Chinese';;
([fF]) echo 'French';;
(*) echo 'Unrecognized language abbreviation';;
esac
如果您需要交换机外的值,您可以在case
中进行规范分配:
read language
case "$language" in
([cC]) lingua='zh_tw'; echo 'Chinese';;
([fF]) lingua='fr_fr'; echo 'French';;
(*) echo 'Unrecognized language abbreviation';;
esac