我试图从下面的列表中获取唯一值,但保留原始顺序中的唯一值。
这是出现的顺序。
group
swamp
group
hands
swamp
pipes
group
bellyful
pipes
swamp
emotion
swamp
pipes
bellyful
after
bellyful
Run Code Online (Sandbox Code Playgroud)
我试过组合sort和uniq命令,但输出按字母顺序排序,如果我不使用排序命令,uniq 命令不起作用。
$ sort file | uniq
after
bellyful
emotion
group
hands
pipes
swamp
Run Code Online (Sandbox Code Playgroud)
我想要的输出是这样的
group
swamp
hands
pipes
bellyful
emotion
after
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
一个简短的、拥挤的 awk 调用将完成工作。我们将创建一个关联数组,并在每次看到一个单词时进行计数:
$ awk '!count[$0]++' file
group
swamp
hands
pipes
bellyful
emotion
after
Run Code Online (Sandbox Code Playgroud)
解释:
$0是当前行。count是一个关联数组,将行映射到我们看到它们的次数。awk 不介意我们访问未初始化的变量。当我们第一次访问它们时,它会自动创建count一个数组并将元素设置为0。count[$0]是0,我们否定它!0 == 1。如果我们再次看到这个词count[$0]是肯定的,否定的给出0。expr { actions; }. 当表达式为真时,采取行动。但动作可以省略;如果我们不写,默认操作是{ print; }.| 归档时间: |
|
| 查看次数: |
132 次 |
| 最近记录: |