LeetCode //Bash - 192. Word Frequency

192. 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.
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

From: LeetCode

Link: 192. Word Frequency


Solution:

Ideas:
  1. cat words.txt reads the content of words.txt.
  2. tr -s ' ' '\n' replaces one or more spaces with a newline character, so each word is on a new line.
  3. sort sorts the words alphabetically.
  4. uniq -c counts the occurrences of each unique word.
  5. sort -nr sorts the lines in numerical reverse order based on the count.
  6. awk '{print 2, 1}' reorders the output to show the word first and its frequency second.
Code:
bash 复制代码
cat words.txt | tr -s ' ' '\n' | sort | uniq -c | sort -nr | awk '{print $2, $1}'
相关推荐
玩镜的码农小师兄3 小时前
[从零开始面试算法] (04/100) LeetCode 136. 只出现一次的数字:哈希表与位运算的巅峰对决
c++·算法·leetcode·面试·位运算·hot100
无敌最俊朗@14 小时前
数组-力扣hot56-合并区间
数据结构·算法·leetcode
码农多耕地呗15 小时前
力扣94.二叉树的中序遍历(递归and迭代法)(java)
数据结构·算法·leetcode
微笑尅乐15 小时前
BFS 与 DFS——力扣102.二叉树的层序遍历
leetcode·深度优先·宽度优先
白云千载尽16 小时前
leetcode 912.排序数组
算法·leetcode·职场和发展
代码充电宝16 小时前
LeetCode 算法题【简单】290. 单词规律
java·算法·leetcode·职场和发展·哈希表
And_Ii18 小时前
LeetCode 3397. 执行操作后不同元素的最大数量
数据结构·算法·leetcode
额呃呃18 小时前
leetCode第33题
数据结构·算法·leetcode
dragoooon3418 小时前
[优选算法专题四.前缀和——NO.27 寻找数组的中心下标]
数据结构·算法·leetcode
1白天的黑夜11 天前
递归-24.两两交换链表中的节点-力扣(LeetCode)
数据结构·c++·leetcode·链表·递归