如何在不使用循环的情况下检查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

请在这里帮我

评论
  • 女硬汉
    女硬汉 回复

    Print both arrays as a sorted list, then with comm extract elements present in both lists.

    $ 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
    
    检查另一个数组中是否存在特定元素

    Print the array as list and grep the element.

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

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