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}'
相关推荐
愚润求学7 分钟前
【贪心算法】day7
c++·算法·leetcode·贪心算法
抓饼先生13 小时前
Linux control group笔记
linux·笔记·bash
kevin_cat17 小时前
微信群机器人-备份文件发送通知
git·bash·企业微信
共享家952719 小时前
优先搜索(DFS)实战
算法·leetcode·深度优先
flashlight_hi20 小时前
LeetCode 分类刷题:2563. 统计公平数对的数目
python·算法·leetcode
楼田莉子21 小时前
C++算法专题学习:栈相关的算法
开发语言·c++·算法·leetcode
dragoooon3421 小时前
[数据结构——lesson3.单链表]
数据结构·c++·leetcode·学习方法
Lynnxiaowen21 小时前
今天继续学习shell脚本
linux·运维·学习·云计算·bash
轮到我狗叫了1 天前
力扣.1054距离相等的条形码力扣767.重构字符串力扣47.全排列II力扣980.不同路径III力扣509.斐波那契数列(记忆化搜索)
java·算法·leetcode
hmcjn(小何同学)1 天前
轻松Linux-9.进程间通信
linux·运维·服务器·c++·bash