如何将文件中的数字分组

Jim*_*Jim 4 sed awk perl shell-script text-processing

我有一个带有浮点格式数字的文件。
我可以通过sort -rn numbers.txt | less
我希望能够对它们进行“分组”来查看它们。即很容易看出有多少在同一范围内。
举一个文件的例子:

30.9695041179657  
30.8851490020752  
30.2127060890198  
29.1361880302429  
26.4587681293488   
25.8535399436951   
25.7361891269684   
25.7305450439453   
25.1068568229675   
24.7598769664764   
24.3106801509857   
24.0782940387726   
Run Code Online (Sandbox Code Playgroud)

我不在乎准确性。所以我想知道文件中有多少 25,例如在这种情况下,文件中所有数字的 4 和 30 等。
所以对于这个例子,输出如下:3 代表 30,1 代表 29,1 代表
26,4代表 25,3 代表 24。有没有一种简单的方法来做到这一点?

ste*_*ver 13

怎么样

cut -d. -f1 numbers.txt | sort | uniq -c
Run Code Online (Sandbox Code Playgroud)

使用您的示例数据,

$ cut -d. -f1 numbers.txt | sort | uniq -c
      3 24
      4 25
      1 26
      1 29
      3 30
Run Code Online (Sandbox Code Playgroud)

  • 我会让那个`sort -n` 安全起见。+1,不过。 (2认同)

0xC*_*22L 8

awk( mawk):

$ awk -F . '{COUNTS[$1]++} END{for(ct in COUNTS) {printf("%d %d time(s)\n", ct, COUNTS[ct])}}' test.txt
30 3 time(s)
24 3 time(s)
25 4 time(s)
26 1 time(s)
29 1 time(s)
Run Code Online (Sandbox Code Playgroud)

-F套字段分隔符(FS)来.,比我们经历与所有其他线路{COUNTS[$1]++}使用$1作为小数点分隔符之前的部分(.),并保持我们多少次遇到他们在名为数组中的记录COUNTS

最后 ( END {}) 我们然后转储我们发现的内容。如您所见,最大的部分是输出。

在文件中更具可读性:

{COUNTS[$1]++}
END {
  for(ct in COUNTS)
  {
    printf("%d %d time(s)\n", ct, COUNTS[ct])
  }
}
Run Code Online (Sandbox Code Playgroud)


dev*_*ull 7

你可以使用awk

awk '{a[int($1)]++}END{for (i in a) {print a[i], i}}' inputfile
Run Code Online (Sandbox Code Playgroud)

如果您希望对输出进行排序,请将输出通过管道传输到sort

awk '{a[int($1)]++}END{for (i in a) {print a[i], i}}' inputfile | sort -k2
Run Code Online (Sandbox Code Playgroud)

对于您的样本输入,这将产生:

3 24
4 25
1 26
1 29
3 30
Run Code Online (Sandbox Code Playgroud)