首页 > 解决方案 > 如何在不使用循环的情况下检查 shell 脚本中的数组中是否存在元素

问题描述

我有一个数组 item1,其中包含类似的条目

item1=($(cat abc.txt | grep "exam" |sed 's/.*exam//'|sed 's/^ *//g'|cut -d/ -f2))

所以在这个数组中我有以下条目

abc.raml def.raml xyz.schema check1.json check2.json

现在我想检查这个数组 item1 的每个项目,如果它存在于另一个数组 item2 中

所以我用for循环做了这个

for i in "${item1[@]}"; do
    for j in "${item2[@]}"; do
      if  [[ $i == $j ]]
        then
                echo "file $i present in both arrays"
      fi
    done
done

所以这个循环工作正常..但是我们可以只得到一个单行命令来检查另一个数组中是否存在特定元素而不使用另一个 for 循环

我试过了,但它不工作

for i in "${item1[@]}"; do
  echo ` "${item2[@]}" | grep "$i" `
      if  echo $? == 0
        then
                echo "file $i present in both arrays"
      fi
    done
done

请在这里帮助我

标签: arrayslinuxbashshellunix

解决方案


将两个数组打印为排序列表,然后comm在两个列表中都存在提取元素。

$ item1=(abc.raml def.raml xyz.schema check1.json check2.json)
$ item2=(abc.raml def.raml xyz.schema check1.json check2.json other)

$ comm -12 <(printf "%s\n" "${item1[@]}" | sort) <(printf "%s\n" "${item2[@]}" | sort) | xargs -I{} echo "file {} present in both arrays"
file abc.raml present in both arrays
file check1.json present in both arrays
file check2.json present in both arrays
file def.raml present in both arrays
file xyz.schema present in both arrays

检查特定元素是否存在于另一个数组中

将数组打印为列表和grep元素。

if printf "%s\n" "${item1[@]}" | grep -qxF abc.raml; then
    echo "abc.raml is present in item1"
fi

使用可以包含换行符的数组项时,请使用零分隔流。


推荐阅读