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}'
相关推荐
努力学算法的蒟蒻4 分钟前
day14(11.14)——leetcode面试经典150
算法·leetcode
海琴烟Sunshine4 小时前
leetcode 383. 赎金信 python
python·算法·leetcode
cynicme10 小时前
力扣3228——将 1 移动到末尾的最大操作次数
算法·leetcode
熬了夜的程序员10 小时前
【LeetCode】109. 有序链表转换二叉搜索树
数据结构·算法·leetcode·链表·职场和发展·深度优先
Miraitowa_cheems13 小时前
LeetCode算法日记 - Day 102: 不相交的线
数据结构·算法·leetcode·深度优先·动态规划
Miraitowa_cheems13 小时前
LeetCode算法日记 - Day 101: 最长公共子序列
数据结构·算法·leetcode·深度优先·动态规划
玖剹15 小时前
二叉树递归题目(一)
c语言·c++·算法·leetcode
沧澜sincerely15 小时前
BFS & 图论【各种题型+对应LeetCode习题练习】
leetcode·图论·广度优先
不穿格子的程序员15 小时前
从零开始写算法——二分-寻找旋转排序数组中的最小值
数据结构·算法·leetcode·二分查找
小白程序员成长日记15 小时前
2025.11.13 力扣每日一题
算法·leetcode·职场和发展