我有一个具有6个值的数组,然后又有三个数组,其值在4到1之间。我想遍历数组1,并检查数组1的值是否出现在数组2,数组3和数组4中。目前,我具有以下内容,但它似乎只是针对数组2,3和3中的第一个值检查数组1的值4.我省略了数组3和4,但是它们的for循环与array2相同,并且位于array1的循环内。
array1=("value1" "value2" "value3" "value4" "value5" "value6")
for i in "${array1}"; do
array2= ("value1" "value3" "value4" "value5")
for f in "${array2}; do
if [[ ${i} == ${f} ]]; then
echo "${i} in array1 matches ${f} in array2"
else
echo "${i} in array1 does not match any value in array2"
fi
done
done
答案 0 :(得分:0)
我认为最好的办法就是创建一个函数
in_array () {
search=$1
shift # remove first argument from list of args $@
for val; do # equivalent to `for val in "$@"`
if [[ $search = $val ]]; then
return # returns exit code of the successful [[ test ]], 0
fi
done
return 1
}
如果找到该值,则返回0
,否则返回1
,使您可以像这样使用它:
array1=("value1" "value2" "value3" "value4" "value5" "value6")
array2=("value1" "value3" "value4" "value5")
for i in "${array1[@]}"; do
if in_array "$i" "${array2[@]}"; then
echo "$i in array1 is in array2"
fi
done
请注意,要遍历数组的所有值,正确的扩展名为"${array[@]}"
(带双引号和[@]
)。
答案 1 :(得分:0)
这可以在一个循环中完成:
#!/usr/bin/env bash
array1=("value1" "value2" "value3" "value4" "value5" "value6")
array2=("value1" "value3" "value4" "value5")
while read -r -d '' -n 8 count && IFS= read -r value; do
if [ "$count" -gt 1 ]; then
# value is seen more than once, so it is in both arrays
echo "${value} in array1 matches ${value} in array2"
else
# value is only seen once
if printf $'%s\n' "${array1[@]}" | grep --quiet "$value"; then
# value is from array1
echo "${value} in array1 does not match any value in array2"
fi
fi
done< <(
# Combine both arrays
# Sort and count number of times each value appears
# then feed the while loop
printf $'%s\n' "${array1[@]}" "${array2[@]}" | sort | uniq --count
)