Shell练习 统计单词个数,降序排列
2016-04-02 23:51
609 查看
原文:https://leetcode.com/problems/word-frequency/ Write a bash script to calculate the frequency of each word in a text file words.txt. For simplicity sake, you may assume: words.txt contains only lowercase characters and space ' ' characters. Each word must consist of lowercase characters only. Words are separated by one or more whitespace characters. For example, assume that words.txt has the following content: the day is sunny the the the sunny is is Your script should output the following, sorted by descending frequency: the 4 is 3 sunny 2 day 1 简单点就是说给你一个文件,里面是又空格【可以有多个】分割好的单词【都是小写】,请统计一下不同单词的个数,并降序输出。
将单词记录到数组中,之后遍历输出,使用sort排序,指定第2列按数字降序,即可。
答案:
awk '{for(i=1;i<=NF;i++) num[$i]++;} END{ for(k in num) print k" "num[k]}' words.txt|sort -rnk 2
使用sort排序,指定哪一列使用-k,后面跟数字,按数字进行排序,使用-n,降序排列使用-r。
相关文章推荐
- Shell练习 行列转换
- linux下如何用c语言调用shell命令
- Powershell管理DHCP作用域
- HDFS的Shell命令
- 控制台,终端,虚拟终端,tty,shell等概念的区别
- Linux进阶之bash编程四(内置变量)
- shell编程入门
- shell 脚本执行日志通用模块
- Shell特殊变量: $0, $#, $*, $@, $?, $$, $!, $_和命令行参数$n
- Hbase shell <一>
- shell script
- bash shell的操作环境
- shell的变量功能
- shell脚本实现检測回文字符串
- linux shell常用快捷键 通配符
- Linux_Shell初级编程入门
- Shell脚本
- Linux C实现简单的shell
- shell、C中mysql插入数据语句
- Mac 下新建 .bash_profile 文件