行长计数bash

时间:2014-03-26 08:19:24

标签: bash awk uniq

如果我有一个包含

的示例文件
11
11
0
11
11
11
11
0

并运行uniq -c命令为什么它会将我作为输出

2 11
1 0
4 11
1 0

而不是

6 11
2 0

如何按上述方式输出输出,而不是将其分成奇怪的组

4 个答案:

答案 0 :(得分:5)

您的问题已在手册中得到解答。输入需要排序。

The uniq utility reads the standard input comparing adjacent lines, and
writes a copy of each unique input line to the standard output.  The sec-
ond and succeeding copies of identical adjacent input lines are not writ-
ten.  Repeated lines in the input will not be detected if they are not
adjacent, so it may be necessary to sort the files first.

说:

sort inputfile | uniq -c

答案 1 :(得分:1)

您可以使用awk

awk '{a[$0]++} END {for (i in a) print a[i],i}' file
6 11
2 0

答案 2 :(得分:0)

您应该先对文件进行排序。所以以下命令会有所帮助:

  

sort test.txt | uniq -c

这会给你以下输出:

  

2 0

     

6 11

您可能还需要使用不同的排序选项。

答案 3 :(得分:0)

只需一个命令即可完成

  

sort -u filetosort.txt