如何删除bash中现有数组中的重复元素? [英] How to remove duplicate elements in an existing array in bash?

查看:47
本文介绍了如何删除bash中现有数组中的重复元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建仅包含Array中存在的唯一元素的newArray?

How do I create a newArray containing only the unique elements present in Array?

Ex:ARRAY分别在ARRAY [0-5]处包含元素 aa ab bb aa ab cc .

Ex: ARRAY contains elements aa ab bb aa ab cc at ARRAY[0-5] respectively.

当我打印newARRAY时,我只希望分别在newARRAY [0-3]上分别 aa ab bb cc .

When I print newARRAY, I want only aa ab bb cc at newARRAY[0-3] respectively.

我已经搜索了一段时间的堆栈溢出,但是没有任何东西可以解决我的问题.我试图做 newARRAY = $(ARRAY [@] | sort -u | uniq ,但是重复的元素仍然存在.

I've searched stack overflow for a while now and nothing is solving my problem. I tried to do newARRAY=$(ARRAY[@] | sort -u | uniq, but duplicated elements still exist.

推荐答案

天真的方法

要获取 arr 的唯一元素,并假设没有元素包含换行符,则:

Naive approach

To get the unique elements of arr and assuming that no element contains newlines:

$ printf "%s\n" "${arr[@]}" | sort -u
aa
ab
bb
cc

更好的方法

要获得一个以NUL分隔的列表,即使有换行符,该列表也可以使用:

Better approach

To get a NUL-separated list that works even if there were newlines:

$ printf "%s\0" "${arr[@]}" | sort -uz
aaabbbcc

(这当然在终端上看起来很丑,因为它不显示NUL.)

(This, of course, looks ugly on a terminal because it doesn't display NULs.)

要在 newArr 中捕获结果:

$ newArr=(); while IFS= read -r -d '' x; do newArr+=("$x"); done < <(printf "%s\0" "${arr[@]}" | sort -uz)

运行上述命令后,我们可以使用 declare 来验证 newArr 是我们想要的数组:

After running the above, we can use declare to verify that newArr is the array that we want:

$ declare -p newArr
declare -a newArr=([0]="aa" [1]="ab" [2]="bb" [3]="cc")

对于那些喜欢将代码分散在多行上的人,可以将以上内容重写为:

For those who prefer their code spread over multiple lines, the above can be rewritten as:

newArr=()
while IFS= read -r -d '' x
do
    newArr+=("$x")
done < <(printf "%s\0" "${arr[@]}" | sort -uz)

其他评论

请勿将所有大写字母用作变量名.系统和外壳程序使用所有大写字母作为名称,并且您不希望意外覆盖其中之一.

Additional comment

Don't use all caps for your variable names. The system and the shell use all caps for their names and you don't want to accidentally overwrite one of them.

这篇关于如何删除bash中现有数组中的重复元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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