如何仅打印 BASH 中的唯一行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23740545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 00:51:24  来源:igfitidea点击:

How to print only the unique lines in BASH?

bashuniq

提问by Village

How can I print only those lines that appear exactly once in a file? E.g., given this file:

如何仅打印在文件中仅出现一次的那些行?例如,给定这个文件:

mountain
forest
mountain
eagle

The output would be this, because the line mountainappears twice:

输出是这样的,因为该行mountain出现了两次:

forest
eagle
  • The lines can be sorted, if necessary.
  • 如有必要,可以对行进行排序。

采纳答案by anubhava

Using awk:

使用 awk:

awk '{!seen[
sort inputfile | uniq -u
]++};END{for(i in seen) if(seen[i]==1)print i}' file eagle forest

回答by devnull

Use sortand uniq:

使用sortuniq

   -u, --unique
          only print unique lines

The -uoption would cause uniqto print only unique lines. Quoting from man uniq:

-u选项将导致uniq仅打印唯一的行。引自man uniq

eagle
forest

For your input, it'd produce:

对于您的输入,它会产生:

##代码##

Obs:Remember to sortbefore uniq -ubecause uniqoperates on adjacentlines. So what uniq -uactually does is to print lines that don't have identical neighbor lines, but that doesn't mean they are really unique. When you sort, all the identical lines get grouped together and only the lines that are reallyunique in the file will remain after uniq -u.

Obs:记住sort之前,uniq -u因为uniq相邻的行上操作。所以uniq -u实际上做的是打印没有相同相邻线的线,但这并不意味着它们真的是独一无二的。当你sort,所有相同的行被组合在一起,只有在文件中真正独特的行会保留在uniq -u.

回答by Oliver Matthews

You almost had the answer in your question:

你的问题几乎有了答案:

sort filename | uniq -u

sort filename | uniq -u