arrays - 如何在不使用循环的情况下检查 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
请在这里帮助我
解决方案
将两个数组打印为排序列表,然后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
使用可以包含换行符的数组项时,请使用零分隔流。
推荐阅读
- python - 如何在mac上使用python更改文件的创建日期?
- r - ddply {plyr} 中的错误:向量(类型,长度)中的错误:向量:无法创建模式为“NULL”的向量。它是一个错误吗?
- python - 如何转换瞻博网络配置备份文件
- activemq-artemis - 如何更改 ActiveMQ Artemis 代理中的运行时日志记录
- php - 在 Magento 2 中以编程方式将产品添加到购物车
- python - 如何根据使用熊猫的条件重新调整一列数字
- xml - 在 Oracle 中从这个 XML 中提取价值的正确方法是什么?
- java - 如何使用 Java 跟踪从方法到方法的 Java 流
- regex - Bash grep 正则表达式包括减号作为字符集
- javascript - 日期在 JS 日期应用程序中未正确显示