如何仅打印 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
How to print only the unique lines in BASH?
提问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 mountain
appears 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 sort
and uniq
:
使用sort
和uniq
:
-u, --unique
only print unique lines
The -u
option would cause uniq
to print only unique lines. Quoting from man uniq
:
该-u
选项将导致uniq
仅打印唯一的行。引自man uniq
:
eagle
forest
For your input, it'd produce:
对于您的输入,它会产生:
##代码##Obs:Remember to sort
before uniq -u
because uniq
operates on adjacentlines. So what uniq -u
actually 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