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}'
相关推荐
轮到我狗叫了4 分钟前
力扣310.最小高度树(拓扑排序,无向图),力扣.加油站力扣.矩阵置零力扣.二叉树中的最大路径和
算法·leetcode·职场和发展
爱coding的橙子17 分钟前
算法刷题Day9 5.18:leetcode定长滑动窗口3道题,结束定长滑动窗口,用时1h
算法·leetcode·职场和发展
小刘不想改BUG2 小时前
LeetCode LCR 010 和为 K 的子数组 (Java)
java·算法·leetcode
小雅痞3 小时前
[Java][Leetcode middle] 12. 整数转罗马数字
java·linux·leetcode
Espresso Macchiato3 小时前
Leetcode 3551. Minimum Swaps to Sort by Digit Sum
leetcode·排序·leetcode medium·leetcode 3551·leetcode周赛450
緈福的街口15 小时前
【leetcode】2900. 最长相邻不相等子序列 I
算法·leetcode·职场和发展
进击的小白菜15 小时前
LeetCode 153. 寻找旋转排序数组中的最小值:二分查找法详解及高频疑问解析
数据结构·算法·leetcode
緈福的街口18 小时前
【leetcode】144. 二叉树的前序遍历
算法·leetcode
Dream it possible!19 小时前
LeetCode 热题 100_寻找重复数(100_287_中等_C++)(技巧)(暴力解法;哈希集合;二分查找)
c++·leetcode·哈希算法
小羊在奋斗1 天前
【LeetCode 热题 100】二叉树的最大深度 / 翻转二叉树 / 二叉树的直径 / 验证二叉搜索树
算法·leetcode·职场和发展