如何按外观顺序打印唯一值?

Ger*_*Cas 5 bash unique

我试图从下面的列表中获取唯一值,但保留原始顺序中的唯一值。

这是出现的顺序。

group
swamp
group
hands
swamp
pipes
group
bellyful
pipes
swamp
emotion
swamp
pipes
bellyful
after
bellyful
Run Code Online (Sandbox Code Playgroud)

我试过组合sortuniq命令,但输出按字母顺序排序,如果我不使用排序命令,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)

我怎样才能做到这一点?

Joh*_*ica 7

一个简短的、拥挤的 awk 调用将完成工作。我们将创建一个关联数组,并在每次看到一个单词时进行计数:

$ awk '!count[$0]++' file
group
swamp
hands
pipes
bellyful
emotion
after
Run Code Online (Sandbox Code Playgroud)

解释:

  1. awk 一次处理文件一行,并且$0是当前行。
  2. count是一个关联数组,将行映射到我们看到它们的次数。awk 不介意我们访问未初始化的变量。当我们第一次访问它们时,它会自动创建count一个数组并将元素设置为0
  3. 每次看到特定行时,我们都会增加计数。
  4. 我们希望整个表达式在我们第一次看到一个词时评估为真,并且每次都为假。如果为真,则打印该行。当它为假时,该行被忽略。我们第一次看到一个词count[$0]0,我们否定它!0 == 1。如果我们再次看到这个词count[$0]是肯定的,否定的给出0
  5. 为什么 true 表示该行已打印?我们使用的一般语法是expr { actions; }. 当表达式为真时,采取行动。但动作可以省略;如果我们不写,默认操作是{ print; }.