我有一个包含一系列数字的数组:
10213
20223
30843
50981
60934
我该怎么做才能检查数组是否有以数字 4 开头的元素?
for element in array; do
if # $element starts with 4
then
echo "The data exists"
else
echo "No data"
fi
done
答案1
如果数字已经在 bash 数组中,您可以执行以下操作:
msg="There are no numbers starting with '4' in the array."
for num in "${array[@]}"; do
if [[ $num =~ ^4 ]]; then
msg="The array contains an element starting with 4"
break
fi
done
echo "$msg"
或者,如果你喜欢更短、更神秘的解决方案:
printf '%s\n' "${array[@]}" | grep -q ^4 && echo "Yes" || echo "No"