查找两个Bash阵列之间共有的项

时间:2018-04-24 03:46:56

标签: arrays linux bash shell

我有下面的shell脚本,其中有两个数组number1number2。我有一个变量range,其中包含数字列表。

现在我需要弄清楚number1数组中range数组中的所有数字都存在于number2变量中。同样对于number1=(1220 1374 415 1097 1219 557 401 1230 1363 1116 1109 1244 571 1347 1404) number2=(411 1101 273 1217 547 1370 286 1224 1362 1091 567 561 1348 1247 1106 304 435 317) range=90,197,521,540,552,554,562,569:570,573,576,579,583,594,597,601,608:609,611,628,637:638,640:641,644:648 range_f=" "$(eval echo $(echo $range | perl -pe 's/(\d+):(\d+)/{$1..$2}/g;s/,/ /g;'))" " echo "$range_f" for item in "${number1[@]}"; do if [[ $range_f =~ " $item " ]] ; then new_number1+=($item) fi done echo "new list: ${new_number1[@]}" for item in "${number2[@]}"; do if [[ $range_f =~ " $item " ]] ; then new_number2+=($item) fi done echo "new list: ${new_number2[@]}" 数组也是如此。下面是我的shell脚本,它运行正常。

new_number1

有没有更好的方法来写上面的东西?截至目前,我有两个for循环迭代,然后找出new_number2644:648数组。

注意:import numpy as np n = 100 np.random.seed(2) A = np.random.rand(n,n) global_best = np.inf for i in range(n-2): for j in range(i+1, n-1): for k in range(j+1, n): # find the maximum of the element-wise minimum of the three vectors local_best = np.amax(np.array([A[i,:], A[j,:], A[k,:]]).min(0)) # if local_best is lower than global_best, update global_best if (local_best < global_best): global_best = local_best save_rows = [i, j, k] print global_best, save_rows 这样的数字意味着,它以644开头,以648结尾。它只是简短形式。

2 个答案:

答案 0 :(得分:2)

您可以使用mapfile -t new_number1 < <(comm -12 <(printf '%s\n' "${number1[@]}" | sort) <(printf '%s\n' $range_f | sort)) mapfile -t new_number2 < <(comm -12 <(printf '%s\n' "${number2[@]}" | sort) <(printf '%s\n' $range_f | sort)) 进行流程替换而不是循环:

mapfile -t name
  • printf ... | sort从嵌套进程替换读入命名数组
  • comm -12对提供comm
  • 的排序输入流
  • {{1}}会发出两个流共有的项目

答案 1 :(得分:0)

除了codeforester的回答,我还可以考虑另外两种方法:

  1. $range的值加载为关联数组的键。该 值为1。循环遍历${number1[@]}的每个成员 ${number2[@]},根据关联中的值对其进行测试 阵列。
  2. 使用codeforester的printf ... | sort技巧,但管道列表 和范围通过sort | uniq -c,然后grep为 重复。
  3. 我不确定这些中的任何一个是否对您的代码有实际改进。 ...我会创建一个'find duplicates'hell函数,但是否则你的代码看起来很稳定。

相关问题