如何比较两个数组并在shell脚本中显示结果?
假设我们有两个数组如下:
list1=( 10 20 30 40 50 60 90 100 101 102 103 104)
list2=( 10 20 30 40 50 60 70 80 90 100 )
字符串
我的要求是按顺序比较这两个数组,结果只显示为从list1
到(101 102 103 104)
。它不应该包括值70
和80
,这些值存在于list2
中,但不存在于list1
中。
这并没有帮助,因为它包含了所有内容:
echo "${list1[@]}" "${list2[@]}" | tr ' ' '\n' | sort | uniq -u
型
我在下面做了这样的尝试,但为什么不起作用?
list1=( 10 20 30 40 50 60 70 90 100 101 102 103 104)
list2=( 10 20 30 40 50 60 70 80 90 100 )
for (( i=0; i<${#list1[@]}; i++ )); do
for (( j=0; j<${#list2[@]}; j++ )); do
if [[ ${list1[@]} == ${list2[@] ]]; then
echo 0
break
if [[ ${#list2[@]} == ${#list1[@]-1} && ${list1[@]} != ${list2[@]} ]];then
echo ${list3[$i]}
fi
fi
done
done
型
3条答案
按热度按时间ifsvaxew1#
你可以使用
comm
来实现:字符串
导致
型
或者,要获得所需的格式,
型
comm -23
接受两个排序后的文件(这里使用sort
),并打印第一个文件所特有的每一行;进程替换用于将列表馈送到comm
中。然后,
readarray
读取输出,并将每行放入unique
数组的一个元素中。(请注意,这需要Bash。)您的尝试失败了,原因之一是您试图在一次比较中比较多个元素:
型
扩展到
型
而Bash则抱怨应该使用二元运算符,而不是第二个元素
20
。yqkkidmi2#
也可以用这种方法
字符串
输出为
型
希望能帮上忙
编辑
如果2个列表相同:
型
drnojrws3#
ksh关联数组很方便:
个字符
或者类似地,从list1的所有内容开始,删除list2中的内容:
型