比较/ bash中两个数组的区别 [英] Compare/Difference of two arrays in bash

查看:338
本文介绍了比较/ bash中两个数组的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能采取在bash两个数组的差别。结果
将是非常巨大的,如果你可以建议我做它的方式。

Is it possible to take the difference of two arrays in bash.
Would be really great if you could suggest me the way to do it.

code:

Array1=( "key1" "key2" "key3" "key4" "key5" "key6" "key7" "key8" "key9" "key10" )
Array2=( "key1" "key2" "key3" "key4" "key5" "key6" ) 

Array3 =diff(Array1, Array2)

Array3 ideally should be :
Array3=( "key7" "key8" "key9" "key10" )

鸭preciate你的帮助。

Appreciate your help.

推荐答案

如果你想严格数组1 - ARRAY2 ,然后


$ Array3=()
$ for i in "${Array1[@]}"; do
>     skip=
>     for j in "${Array2[@]}"; do
>         [[ $i == $j ]] && { skip=1; break; }
>     done
>     [[ -n $skip ]] || Array3+=("$i")
> done
$ declare -p Array3

运行时可能与关联数组得到改善,但我个人不会理会。如果你正在操作要做到这事足够的数据,外壳是错误的工具。

Runtime might be improved with associative arrays, but I personally wouldn't bother. If you're manipulating enough data for that to matter, shell is the wrong tool.

对于喜欢丹尼斯的回答对称的差异,现有的工具,如 通讯 工作,只要我们的按摩输入和输出位(因为他们对基于行的文件工作,而不是shell变量)。

For a symmetric difference like Dennis's answer, existing tools like comm work, as long as we massage the input and output a bit (since they work on line-based files, not shell variables).

在这里,我们告诉shell使用换行符到阵列连接成一个字符串,并读取从通讯线路时回一个数组舍弃标签页。

Here, we tell the shell to use newlines to join the array into a single string, and discard tabs when reading lines from comm back into an array.


$ oldIFS=$IFS IFS=$'\n\t'
$ Array3=($(comm -3 <(echo "${Array1[*]}") <(echo "${Array2[*]}")))
comm: file 1 is not in sorted order
$ IFS=$oldIFS
$ declare -p Array3
declare -a Array3='([0]="key7" [1]="key8" [2]="key9" [3]="key10")'

据抱怨,因为通过lexographical排序,键1&LT; ...&LT; key9&GT; key10 。但由于两个输入数组排序相似,它也可以忽略该警告。您可以使用 - NOCHECK订单来摆脱警告,或添加 |排序-u &LT内部;(...)进程替换如果你不能保证秩序和放大器;输入数组的唯一性。

It complains because, by lexographical sorting, key1 < … < key9 > key10. But since both input arrays are sorted similarly, it's fine to ignore that warning. You can use --nocheck-order to get rid of the warning, or add a | sort -u inside the <(…) process substitution if you can't guarantee order&uniqueness of the input arrays.

这篇关于比较/ bash中两个数组的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆