出于某种原因使用"读-a"我的脚本只将该行的第一个元素放入数组中。例如,当输入诸如"加拿大中国"之类的字符串时,程序的输出只是读取:
canada
c
Canada changed to uppercase.
而不是:
canada China
c
Canada Changed to uppercase.
C
China Already uppercase.
我的任务说明如下:
创建一个脚本,读取用户的输入并将其存储在Array中。然后,循环遍历数组并:
这是我的代码:
#!/bin/bash
declare -A converterArray
converterArray=([a]=A [b]=B [c]=C [d]=D [e]=E [f]=F [g]=G [h]=H [i]=I [j]=J [k]=K [l]=L [m]=M [n]=N [o]=O [p]=P [q]=Q [r]=R [s]=S [t]=T [u]=U [v]=V [w]=W [x]=X [y]=Y [z]=Z)
read -p "Enter elements separated by space, return to end: " -a inputArray
lowercasemsg=" Changed to uppercase."
uppercasemsg=" Already uppercase."
notlettermsg=" Doesn't start with a letter."
echo $inputArray
for word in $inputArray; do
firstchar=${word:0:1}
echo $firstchar
case $firstchar in
[a-z]*)
word = ${converterArray[$firstchar]}${word:1}
echo $word$lowercasemsg
;;
[A-Z]*)
echo $word$uppercasemsg
;;
*)
echo $word$notlettermsg
;;
esac
done
编辑:感谢John的帮助,问题已经解决了。我还修复了检查字母大小写的问题([a-z]与[[:lower:]]),并删除了不必要的" echos"用于调试。
#!/bin/bash
declare -A converterArray
converterArray=([a]=A [b]=B [c]=C [d]=D [e]=E [f]=F [g]=G [h]=H [i]=I [j]=J [k]=K [l]=L [m]=M [n]=N [o]=O [p]=P [q]=Q [r]=R [s]=S [t]=T [u]=U [v]=V [w]=W [x]=X [y]=Y [z]=Z)
read -p "Enter elements separated by space, return to end: " -a inputArray
lowercasemsg=" Changed to uppercase."
uppercasemsg=" Already uppercase."
notlettermsg=" Doesn't start with a letter."
for word in "${inputArray[@]}"; do
firstchar=${word:0:1}
case $firstchar in
[[:lower:]]*)
inputString=${converterArray[$firstchar]}${word:1}
echo $word$lowercasemsg
;;
[[:upper:]]*)
echo $word$uppercasemsg
;;
*)
echo $word$notlettermsg
;;
esac
done
(第二编辑:固定行,我忘了在等号周围放置空格,最初在之前的编辑中遗忘)
答案 0 :(得分:2)
如果$array
是数组,"${array[@]}"
会给出所有数组元素。裸$array
仅引用第一个元素。
echo "${inputArray[@]}"
for word in "${inputArray[@]}"; do
...
done