我有一个像这样的字符串:
array_string="a b"
我有一个像这样的数组:
array=(a b c)
如果要验证array_string的所有元素是否都包含在数组中,我可以用array_string中包含的元素覆盖数组:
array=($array_string)
哪种是进行这种验证的最佳方法?
答案 0 :(得分:2)
您可以将grep
与两个流程替换一起使用:
grep -qvf <(printf '%s\n' "${array[@]}") <(echo "${array_string// /$'\n'}") ||
echo "all elements of array_string are present in array"
答案 1 :(得分:2)
对于字符串到数组的比较,下面的示例使用空格作为分隔符,并期望它位于列表的开头和结尾,以便每个值都将被包裹在两个分隔符之间。它还避免了使用外部进程或子Shell。
for ((index=0; index < "$((${#array[@]}"; index++)); do
if [[ "$array_string" != *" ${array[$index]} "* ]]; then
return 1
fi
done
对于数组到数组的比较,在删除前导分隔符之后,很容易将字符串转换为数组,然后使用嵌套循环比较它们。这也可以避免使用外部进程或子Shell,因为读取的内容是bash builtin:
# Needs to read to a different variable so it
# doesn't empty the source and read nothing.
IFS=' ' read -ra string_array <<< "${array_string# }"
found=1
for ((x=0; x < "${#string_array[@]}"; x++)); do
for ((y=0; y < "${#array[@]}"; y++)); do
if [[ "${string_array[$x]}" == "${array[$y]}" ]]; then
found=0
fi
done
if [[ found -ne 0 ]]; then
return 1
fi
found=1
done
答案 2 :(得分:0)
您可以像这样确定array_string
中存在但array
中不存在的项目:
join -v1 <(sort -b <<< "${array_string// /$'\n'}") <(IFS=$'\n'; sort -b <<< "${array[*]}")
假定项目不包含空格。 使用此功能,您可以执行以下操作:
if [[ -z $(join -v1 <(sort -b <<< "${array_string// /$'\n'}") <(IFS=$'\n'; sort -b <<< "${array[*]}")) ]]
then
echo "array_string is a subset of array"
else
echo "array_string is NOT a subset of array"
fi