在 shell 脚本中获取 2 个数组中的公共值 [英] Get common values in 2 arrays in shell scripting

查看:56
本文介绍了在 shell 脚本中获取 2 个数组中的公共值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个

array1 = (20,30,40,50)
array2 = (10,20,30,80,100,110,40)

我必须从数组 3 中的这 2 个数组中获取公共值,例如:

I have to get the common values from these 2 arrays in my array 3 like:

array3 = (20,30,40) 

按升序排列.

推荐答案

Shell 和标准 Unix 实用程序擅长处理文本文件.

Shell and standard Unix utilities are good at dealing with text files.

在那个领域,数组是文本文件,其元素是行.

In that realm, arrays would be text files whose elements are the lines.

要找到两个这样的数组之间的公共部分,可以使用标准的 comm 命令.comm 需要按字母顺序排序的输入.

To find the common part between two such arrays, there's the standard comm command. comm expects alphabetically sorted input though.

因此,如果您有两个文件 AB 包含这两个数组的元素,则每行一个(这也意味着数组元素不能包含换行符字符),你可以找到与

So, if you have two files A and B containing the elements of those two arrays, one per line (which also means the array elements can't contain newline characters), you can find the intersection with

comm -12 <(sort A) <(sort B)

如果您想从 bash 数组开始(但在 shell 中使用数组通常很好地表明您使用了错误的工具来完成您的任务),您可以在bash 数组和带有 printf '%s\n' 和分词的 文本文件行数组:

If you want to start with bash arrays (but using arrays in shells is generally a good indication that you're using the wrong tool for your task), you can convert back and forth between the bash arrays and our text file arrays of lines with printf '%s\n' and word splitting:

array_one=(20 30 40 50)
array_two=(10 20 30 80 100 110 40)
IFS=$'\n'; set -f
intersection=($(comm -12 <(
   printf '%s\n' "${array_one[@]}" | sort) <(
   printf '%s\n' "${array_two[@]}" | sort)))

这篇关于在 shell 脚本中获取 2 个数组中的公共值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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