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

如何更改變數中字串的大小寫(大寫和小寫)?
"Enter test: "
read test

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

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

答案1

只需使用標準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,kshzsh(支援該非標準[[...]]語法的 3 個 shell),您可以聲明一個小寫多變的:

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

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

答案2

有幾種有用的方法可以實現這一目標(參見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

讓 shell 忽略大小寫

echo -n "Enter test: "
read test

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

答案3

做這件事有很多方法。如果您使用的是最新版本的 bash,則非常簡單:您可以轉換 的大小寫test,或者可以使用正規表示式來匹配大寫和小寫 a。

首先是正規表示式方式:

read -p "enter test: " test;[[ $test =~ ^[Aa]$ ]] && echo yes || echo no

現在是大小寫轉換:

read -p "enter test: " test;[[ ${test^^} = A ]] && echo yes || echo no

答案4

sed -ne '/^[aA]$/!i\' -e failed -e 's//worked/p;q' </dev/tty

相關內容