从文件生成直方图

Jav*_*ier 41 bash shell awk file

如果输入文件每行包含一个单独的数字,我怎样才能计算该文件中项目发生的次数?

cat input.txt
1
2
1
3
1
0
Run Code Online (Sandbox Code Playgroud)

期望的输出(=> [1,3,1,1]):

cat output.txt
0 1
1 3
2 1
3 1
Run Code Online (Sandbox Code Playgroud)

如果解决方案也可以扩展为浮动数字,那将会很棒.

Cal*_*leb 79

你的意思是你想要计算一个项目在输入文件中出现的次数?首先对它进行排序(-n如果输入始终是数字,如下所示),然后计算唯一结果.

sort -n input.txt | uniq -c
Run Code Online (Sandbox Code Playgroud)

  • 您使用awk获取订单很好,但您不需要在那里使用猫.你应该学习```运算符来将文件输入程序甚至是循环结构.有关幽默的价值,请参阅[无用的猫奖](http://partmaps.org/era/unix/award.html#cat) (7认同)
  • 我不知道`uniq`命令.我把它改成了`cat input.txt | sort -n | uniq -c | awk'{print $ 2""$ 1}'`,现在我正在获得所需的输出. (2认同)

gle*_*man 11

另外一个选项:

awk '{n[$1]++} END {for (i in n) print i,n[i]}' input.txt | sort -n > output.txt
Run Code Online (Sandbox Code Playgroud)