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}'
相关推荐
山脚ice3 小时前
【CT】LeetCode手撕—704. 二分查找
算法·leetcode
瑜陀4 小时前
2024.06.30 刷题日记
数据结构·算法·leetcode
Star Patrick4 小时前
*算法训练(leetcode)第二十天 | 39. 组合总和、40. 组合总和 II、131. 分割回文串
c++·算法·leetcode
阳光男孩014 小时前
力扣974.和可被K整除的子数组
数据结构·算法·leetcode
青釉Oo4 小时前
峰与谷00
java·数据结构·算法·leetcode
zengy57 小时前
代码随想录打卡第十三天
数据结构·c++·算法·leetcode
孑渡8 小时前
【LeetCode】每日一题:跳跃游戏
python·算法·leetcode·游戏·职场和发展
liulanba8 小时前
leetcode--二叉树中的最长交错路径
linux·算法·leetcode
Puppet__8 小时前
【康复学习--LeetCode每日一题】3115. 质数的最大距离
学习·算法·leetcode
每天努力进步!9 小时前
LeetCode热题100刷题6:160. 相交链表、206. 反转链表、234. 回文链表、141. 环形链表、142. 环形链表 II
c++·算法·leetcode·链表