计算 bash 中每行只有一个字符串的唯一字符串
给定输入文件,
z
b
a
f
g
a
b
...
我想输出每个字符串出现的次数,例如:
z 1
b 2
a 2
f 1
g 1
如何在 bash 脚本中完成此操作?
Given input file
z
b
a
f
g
a
b
...
I want to output the number of occurrences of each string, for example:
z 1
b 2
a 2
f 1
g 1
How can this be done in a bash script?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以
排序
输入并传递到uniq -c
< /a>:如果您想要右侧的数字,请使用
awk
切换它们:或者,在
awk
中完成整个操作:You can
sort
the input and pass touniq -c
:If you want the numbers on the right, use
awk
to switch them:Alternatively, do the whole thing in
awk
:应该做这份工作
should do the job
尝试:
其中 test.txt 是您的输入文件。
Try:
Where test.txt would be your input file.
这是仅
bash
版本(需要 bash 版本 4),使用 关联数组。Here's a
bash
-only version (requires bash version 4), using an associative array.这可能对您有用:
这会按照每个字符串出现的顺序输出它们出现的次数。
This might work for you:
This output the number of occurrences of each string in the order in which they appear.
您可以使用
sort filename | uniq -c
。查看uniq 上的维基百科页面。
You can use
sort filename | uniq -c
.Have a look at the Wikipedia page on uniq.