Shell 腳本 - 檢查單一字元輸入是否為大寫、小寫或特殊字元

Shell 腳本 - 檢查單一字元輸入是否為大寫、小寫或特殊字元

這是我寫的程式碼。我需要一個簡單的程式碼,使用 if elif 檢查讀取的字元是大寫、小寫還是特殊符號。

echo "enter a char"
read c

if [[ $c == [A-Z] ]];
then
    echo "upper"
elif [[ $c == [a-z] ]];
then
    echo "lower"
else 
    echo "Digit or special symbols!"
fi

以下是我輸入字元後收到的輸出

enter a char
A
upper

enter a char
a
Digit or special symbols!

aravind@bionic-beaver:~/Desktop$ ./1.sh
enter a char
1
Digit or special symbols!

答案1

除非你清空$IFS並添加-r選項,read以非常特殊的方式讀取一行輸入

例如,如果使用者輸入" \x ",預設值為$IFS$c將包含x,而不是使用者輸入的內容。

也不[a-z]匹配小寫字母,它匹配語言環境中a和之間的任何類型z(shell 之間的行為存在一些差異。例如,bash在許多語言環境中,包括 A 和 Y 之間的英文字母)。它甚至可以匹配某些語言環境和某些工具中的字元序列。

在這裡,您可能想要:

printf >&2 'Please enter a character: '
IFS= read -r c
case $c in
  ([[:lower:]]) echo lowercase letter;;
  ([[:upper:]]) echo uppercase letter;;
  ([[:alpha:]]) echo neither lower nor uppercase letter;;
  ([[:digit:]]) echo decimal digit;;
  (?) echo any other single character;;
  ("") echo nothing;;
  (*) echo anything else;;
esac

(該語法是 POSIXsh語法,您甚至不需要安裝bash)。

如果您想將其限制為英文字母(拉丁字母中沒有變音符號的字母),您需要單獨命名它們:

([abcdefghijklmnopqrstuvwxyz]) echo English lowercase letter;;

export LC_ALL=C或者在語句之後read和之前將語言環境修復為 C case,但(?)測試將無效,因為它可能錯誤地將某些字元解釋為字元序列。例如,UTF-8é在 C 語言環境中將被視為兩個字元。

答案2

嘗試使用正規表示式測試:

read -p "Type a character" c
if [[ "$c" =~ [a-z] ]]; then
    echo "lowercase"
elif [[ "$c" =~ [A-Z] ]]; then
    echo "uppercase"
else
    echo "Non-alphabetic"
fi

答案3

請務必將變數括在引號中 - 例如,如果您將正規表示式作為字串進行測試,則可以輸入以下內容:

echo "enter a US state name"
read var_1

if [[ "$var_1" =~ [A-Z] ]]; then
    echo "contains a capital letter"
elif [[ "$var_1" =~ [a-z] ]]; then
    echo "contains lower case letters"
else
    echo "contains special characters or numbers"
fi
    

答案4

while read -r line; do
    [[ "${line:0:1}" =~ [[:upper:]] ]] && echo "Started with upper: $line" || echo "$line";
done</path/to/file

相關內容