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}'
相关推荐
v_for_van1 小时前
力扣刷题记录6(无算法背景,纯C语言)
c语言·算法·leetcode
样例过了就是过了2 小时前
LeetCode热题100 最大子数组和
数据结构·算法·leetcode
踩坑记录2 小时前
leetcode hot100 200. 岛屿数量 medium dfs
leetcode·深度优先
dingdingfish3 小时前
Bash学习 - 第6章:Bash Features,第10节:The Restricted Shell
bash·shell·rbash·restrict
追随者永远是胜利者3 小时前
(LeetCode-Hot100)4. 寻找两个正序数组的中位数
java·算法·leetcode·职场和发展·go
追随者永远是胜利者3 小时前
(LeetCode-Hot100)2. 两数相加
java·算法·leetcode·go
程序员酥皮蛋4 小时前
hot 100 第二十九题 29.删除链表的倒数第 N 个结点
数据结构·算法·leetcode·链表
踩坑记录5 小时前
leetcode hot100 994. 腐烂的橘子 medium bfs
leetcode·宽度优先
化学在逃硬闯CS5 小时前
【Leetcode热题100】108.将有序数组转换为二叉搜索树
数据结构·c++·算法·leetcode
追随者永远是胜利者5 小时前
(LeetCode-Hot100)5. 最长回文子串
java·算法·leetcode·职场和发展·go