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}'
相关推荐
Zaly.1 小时前
【Python刷题】LeetCode 1727 重新排列后的最大子矩阵
算法·leetcode·矩阵
memcpy04 小时前
LeetCode 1456. 定长子串中元音的最大数目【定长滑窗模板题】中等
算法·leetcode·职场和发展
玛丽莲茼蒿4 小时前
LeetCode hot100【相交链表】【简单】
算法·leetcode·职场和发展
wen__xvn4 小时前
力扣模拟题刷题
算法·leetcode
不要秃头的小孩4 小时前
力扣刷题——111.二叉树的最小深度
数据结构·python·算法·leetcode
We་ct5 小时前
LeetCode 35. 搜索插入位置:二分查找的经典应用
前端·算法·leetcode·typescript·个人开发
Navigator_Z5 小时前
LeetCode //C - 990. Satisfiability of Equality Equations
c语言·算法·leetcode
lightqjx7 小时前
【算法】前缀和
c++·算法·leetcode·前缀和
窝子面7 小时前
LeetCode练题三:链表
算法·leetcode·链表
y = xⁿ8 小时前
【LeetCodehot100】T108:将有序数组转换为二叉搜索树 T98:验证搜索二叉树
数据结构·算法·leetcode