在bash阵列路口 [英] Array intersection in bash

查看:85
本文介绍了在bash阵列路口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你如何在bash比较两个数组找到所有相交的价值观?

How do you compare two arrays in bash to find all intersecting values?

让我们说:结果
ARRAY1包含的值1和2的结果
数组2包含的值2和3

Let's say:
array1 contains values 1 and 2
array2 contains values 2 and 3

我要拿回2作为一个结果。

I should get back 2 as a result.

我自己的答案,我还不能发布,由于小的声誉:

My own answer, which I can't post yet due to small reputation:

for item1 in $array1; do
    for item2 in $array2; do
        if [[ $item1 = $item2 ]]; then
            result=$result" "$item1
        fi
    done
done

我在寻找替代解决方案也是如此。

I'm looking for alternate solutions as well.

推荐答案

表1的元素被用作常规的前pression在列表2抬头(如pressed为字符串:$ {列表2 [*] }):

The elements of list 1 are used as regular expression looked up in list2 (expressed as string: ${list2[*]} ):

list1=( 1 2 3 4   6 7 8 9 10 11 12)
list2=( 1 2 3   5 6   8 9    11 )

l2=" ${list2[*]} "                    # add framing blanks
for item in ${list1[@]}; do
  if [[ $l2 =~ " $item " ]] ; then    # use $item as regexp
    result+=($item)
  fi
done
echo  ${result[@]}

的结果是

1 2 3 6 8 9 11

这篇关于在bash阵列路口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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