[英]Using a case statement with a for loop in Bash scripting Linux
該腳本應該查看我的參數,並告訴我單詞是否以大寫,小寫或數字開頭。 現在,當我輸入#個單詞時,它告訴我它們都是大寫的。 謝謝。
#!/bin/bash
startwithdigit=0
startwithupper=0
startwithlower=0
startwithother=0
for digit in $@
do
case $@ in
[[:lower:]]* ) startwithlower=$((startwithlower+1)) ;;
[[:upper:]]* ) startwithupper=$((startwithupper+1)) ;;
[[:digit:]]* ) startwithdigit=$((startwithdigit+1)) ;;
esac
done
echo $startwithlower words begin with a lowercase
echo $startwithupper words begin with a capital
echo $startwithdigit words begin with a digit
~~
請嘗試以下操作:
我使用的是if語句而不是大小寫,並且我通過在文件中追加並隨后進行字數計數來進行計數,而不是每次都向計數器添加1。
# Sample data
"India China dubai germany 123 456 666" to the script.
It has 2 uppercase words, 2 lowercase words and 3 digit words.
# Sample output
bash$> ./upper_lower.sh "India China dubai germany 123 456 666"
2 words are lowercase
2 words are uppercase
3 words are digits
# 劇本。
bash$> cat upper_lower.sh
#!/bin/bash
# Main loop to process the words passed to script in ARGV array
for w in $@
do
echo $w | while read word
do
# Matching lowercase only
if [[ $word =~ ^[a-z] ]]
then
echo $word >> aa
fi
# Matching UPPERCASE only
if [[ $word =~ ^[A-Z] ]]
then
echo $word >> bb
fi
# Matching digits only
if [[ $word =~ ^[0-9] ]]
then
echo $word >> cc
fi
done
done
l=`cat aa|wc -l` # Taking lowercase count
u=`cat bb|wc -l` # Taking uppercase count
d=`cat cc|wc -l` # Taking digits count
echo; echo "$l words are lowercase" # Added extra echo just to print new line.
echo; echo "$u words are uppercase"
echo; echo "$d words are digits"
rm aa bb cc # removing temp files after processing
bash$>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.