Bash

如何更改變數中字元串的大小寫(大寫和小寫)?

  • July 26, 2018
"Enter test: "
read test

if [[ $test == "a" ]]; then
   echo "worked"
else
   echo "failed"
fi

這是我正在做的測試的簡單說明,但如果我輸入“A”,它將失敗。在可變階段我可以做些什麼來將其全部更改為小寫,以便測試匹配?

有幾種有用的方法可以實現這一點(在 中bash):

兩張支票

echo -n "Enter test: "
read test

if [[ $test == "a" || $test == "A" ]]; then
   echo "worked"
else
   echo "failed"
fi

使輸入小寫

echo -n "Enter test: "
read test
test="${test,,}"

if [[ $test == "a" ]]; then
   echo "worked"
else
   echo "failed"
fi

兩種情況的正則表達式

echo -n "Enter test: "
read test

if [[ $test =~ ^[aA]$ ]]; then
   echo "worked"
else
   echo "failed"
fi

使外殼忽略大小寫

echo -n "Enter test: "
read test

shopt -s nocasematch
if [[ $test == a ]]; then
   echo "worked"
else
   echo "failed"
fi

只需使用標準sh(POSIX 和 Bourne)語法:

case $answer in
 a|A) echo OK;;
 *)   echo >&2 KO;;
esac

或者:

case $answer in
 [aA]) echo OK;;
 *)    echo >&2 KO;;
esac

使用bash, kshor zsh(支持該非標準[[...]]語法的 3 個 shell),您可以聲明一個小寫變數:

typeset -l test
printf 'Enter test: '
read test
if [ "$test" = a ]; then...

(請注意,bash在某些語言環境中,大小寫轉換是虛假的)。

引用自:https://unix.stackexchange.com/questions/180472