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}'
相关推荐
墨染点香1 小时前
LeetCode 刷题【160. 相交链表】
算法·leetcode·链表
少睡点觉1 小时前
LeetCode 238. 除自身以外数组的乘积 问题分析+解析
java·算法·leetcode
YoungHong19921 小时前
面试经典150题[066]:分隔链表(LeetCode 86)
leetcode·链表·面试
Wenhao.3 小时前
LeetCode 救生艇
算法·leetcode·golang
夏鹏今天学习了吗3 小时前
【LeetCode热题100(69/100)】字符串解码
linux·算法·leetcode
小白程序员成长日记4 小时前
2025.11.18 力扣每日一题
算法·leetcode·职场和发展
未若君雅裁6 小时前
LeetCode 18 - 四数之和 详解笔记
java·数据结构·笔记·算法·leetcode
鱼骨不是鱼翅7 小时前
力扣hot100----1day
python·算法·leetcode·职场和发展
小欣加油7 小时前
leetcode 429 N叉树的层序遍历
数据结构·c++·算法·leetcode·职场和发展
裤裤兔7 小时前
linux提取指定前缀文件到其他文件夹
linux·运维·服务器·bash·终端