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

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

问题描述

可以在bash中使用两个数组的差异。

如果你能建议我这样做,那真是太棒了。



代码:

  Array1 =(key1key2key3key4key5key6 key7key8key9key10)
Array2 =(key1key2key3key4key5key6)

Array3 = diff (array1,array2)

Array3理想地应该是:
Array3 =(key7key8key9key10)
/ pre>

感谢您的帮助。

解决方案

Array1 - Array2

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

可以使用关联数组改进运行时,但我个人不会打扰。






对于像Dennis的对称差异answer, comm 工作,只要我们按下输入和输出一点(因为他们工作在基于行的文件,而不是shell变量)。



shell使用换行符将数组连接成单个字符串,并且当从 comm 读取回到数组时舍弃制表符。

 
$ oldIFS = $ IFS IFS = $'\\\
\t'
$ Array3 =($(comm -3<(echo$ {Array1 [ *]})<(echo$ {Array2 [*]})))
comm:文件1不按排序顺序
$ IFS = $ oldIFS
$ declare - p Array3
declare -a Array3 ='([0] =key7[1] =key8[2] =key9[3] =key10)'

它抱怨,因为通过字典排序, key1< ...< key9> key10 。但是由于两个输入数组的排序是相似的,忽略这个警告是很好的。您可以使用 - nocheck-order 摆脱警告,或者添加 |如果您不能保证输入数组的顺序和唯一性,请在<(...)过程替换中排序-u

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" )

Appreciate your help.

解决方案

If you strictly want Array1 - Array2, then

$ 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.


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).

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")'

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天全站免登陆