有没有一个“集合”? bash 中的数据结构?
Python 有一个“集合”类型,其中包含唯一的对象。 Bash 有类似的东西吗?
我想继续向这样的 bash“集”添加元素,并且永远不要重复。
Python has a "set" type which contains unique objects.
Does Bash have something equivalent?
I want to keep adding elements to such a bash "set" and never have duplicates.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Bash 4.0 具有关联数组,可用于构建集合。
这里有一篇文章讨论了它们(这是第一篇 Google 搜索的“bash 关联数组”)。
(就我个人而言,我只会使用 bash 以外的东西,可能是 Perl。)
Bash 4.0 has associative arrays, which can be used to build sets.
Here's an article that discusses them (it was the first Google hit for "bash associative arrays").
(Personally, I'd just use something other than bash, probably Perl.)
经过一番谷歌搜索后,我在 http:// www.catonmat.net/blog/set-operations-in-unix-shell-simplified/。它以多种方式提供所有常用的集合运算符,甚至还有可打印的 pdf 备忘单。
不过,我使用了关联数组,它更具可读性。
声明一个
setA
关联数组变量:或者同时声明并添加初始成员:
将成员添加到集合中:
测试成员身份:
列出成员(空格分隔):
或(换行符分隔):
迭代成员:
基数(集合中的成员数量):
删除成员:
使用引号添加名称中带有空格的成员:
也可以使用变量作为成员:
After some googling I found a nice bash implementation at http://www.catonmat.net/blog/set-operations-in-unix-shell-simplified/. It has all the usual set operators in multiple ways, and even a printable pdf cheatsheet.
I've used associative arrays though, it's much more readable.
Declare a
setA
associative array variable:Or declare and add the initial members at the same time:
Add a member to the set:
Test for membership:
List members (space separated):
or (newline separated):
Iterate through members:
Cardinality (number of members in the set):
Remove a member:
Use quotes to add members with spaces in their name:
And it's possible to use variables as members too:
在 bash 3 中也给出
,其中没有可用的关联数组
gives
also in bash 3, where no associative arrays are available