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 分钟前
LeetCode经典算法面试题 #238:除自身以外数组的乘积(左右乘积数组法、分治法等多种方法详解)
算法·leetcode·分治法·算法面试·除自身以外数组的乘积·前缀乘积·左右乘积数组法
Ethan-D29 分钟前
每日一题#21 二维 DP + 计数类
java·python·算法·leetcode·动态规划
共享家952733 分钟前
力扣刷题之路
算法·leetcode·深度优先
夏鹏今天学习了吗9 小时前
【LeetCode热题100(82/100)】单词拆分
算法·leetcode·职场和发展
踩坑记录11 小时前
leetcode hot100 189.轮转数组 medium
leetcode
Dream it possible!12 小时前
LeetCode 面试经典 150_二分查找_在排序数组中查找元素的第一个和最后一个位置(115_34_C++_中等)
c++·leetcode·面试
菜鸟233号14 小时前
力扣377 组合总和 Ⅳ java实现
java·数据结构·算法·leetcode
老鼠只爱大米15 小时前
LeetCode算法题详解 189:轮转数组
leetcode·轮转数组·数组旋转·环状替换法·算法面试题
jinmo_C++15 小时前
Leetcode_59. 螺旋矩阵 II
算法·leetcode·矩阵
夏鹏今天学习了吗15 小时前
【LeetCode热题100(81/100)】零钱兑换
算法·leetcode·职场和发展