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}'
相关推荐
圣保罗的大教堂8 小时前
leetcode 2540. 最小公共值 简单
leetcode
i7i8i9com12 小时前
Hermes Agent 安装记录
开发语言·bash·hermes
洛水水13 小时前
【力扣100题】53.最长回文子串
算法·leetcode·职场和发展
过期动态14 小时前
【LeetCode 热题 100】盛最多水的容器
java·数据结构·spring boot·算法·leetcode·spring cloud·职场和发展
凌波粒14 小时前
LeetCode--700.二叉搜索树中的搜索(二叉树)
算法·leetcode·职场和发展
洛水水14 小时前
【力扣100题】58.轮转数组
算法·leetcode
风筝在晴天搁浅15 小时前
阿里 LeetCode 876.链表的中间节点
算法·leetcode·链表
玖釉-15 小时前
二叉树展开为链表:从先序遍历到原地指针重排
c++·windows·算法·leetcode·链表
洛水水15 小时前
【力扣100题】52.最小路径和
算法·leetcode
圣保罗的大教堂15 小时前
leetcode 3043. 最长公共前缀的长度 中等
leetcode