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}'
相关推荐
辰烨chenye6 小时前
LeetCode Hot 100 题解 · 普通数组篇
算法·leetcode·职场和发展
辰烨chenye9 小时前
LeetCode Hot 100 题解 · 二分篇
java·算法·leetcode
带多刺的玫瑰16 小时前
Leecode#26刷题之删除有序数组中的重复项
数据结构·算法·leetcode
wabs66619 小时前
关于二叉树【429.N叉树的层序遍历的思考】
数据结构·c++·算法·leetcode·二叉树
不会就选b19 小时前
算法日常・每日刷题--<贪心>6
数据结构·算法·leetcode
青山木20 小时前
Hot 100 --- 跳跃游戏 II
java·数据结构·算法·leetcode·贪心算法
Tisfy20 小时前
LeetCode 3870.统计范围内的逗号:模拟 或 一步计算
数学·算法·leetcode·题解·模拟·遍历
木井巳21 小时前
【BFS/DFS 解决 FloodFill 算法】衣橱整理
java·算法·leetcode·深度优先·广度优先·宽度优先
shehuiyuelaiyuehao1 天前
算法40,模拟运算,替换所有的问号
数据结构·算法·leetcode