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}'
相关推荐
一去不复返的通信er1 小时前
排序 + 双指针:力扣15三数之和
算法·leetcode
文丑颜不良啊1 小时前
LeetCode1901~1920题目解析
java·leetcode
Pniubi1 小时前
力扣3无重复字符的最长字串(滑动窗口)
算法·leetcode·职场和发展
longzhizhui92620 小时前
Ubuntu 全版本 CVE-2026-98432 内核安全升级操作手册
ubuntu·网络安全·云计算·bash
文丑颜不良啊2 天前
LeetCode1661~1680题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode1721~1740题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode1681~1700题目解析
java·leetcode
开开心心就好2 天前
网页图片批量下载工具,输入链接就保存
服务器·算法·leetcode·支持向量机·pdf·ocr·1024程序员节
圣保罗的大教堂2 天前
leetcode 462. 最小操作次数使数组元素相等 II 中等
leetcode
Navigator_Z2 天前
LeetCode //C - 1313. Decompress Run-Length Encoded List
c语言·算法·leetcode