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}'
相关推荐
源代码•宸2 小时前
Leetcode—620. 有趣的电影&&Q3. 有趣的电影【简单】
数据库·后端·mysql·算法·leetcode·职场和发展
XFF不秃头6 小时前
力扣刷题笔记-旋转图像
c++·笔记·算法·leetcode
yaoh.wang9 小时前
力扣(LeetCode) 111: 二叉树的最小深度 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·深度优先
努力学算法的蒟蒻10 小时前
day42(12.23)——leetcode面试经典150
算法·leetcode·面试
鹿角片ljp10 小时前
力扣226.翻转二叉树-递归
数据结构·算法·leetcode
iAkuya11 小时前
(leetcode)力扣100 21搜索二维矩阵2(z型搜索)
linux·leetcode·矩阵
(●—●)橘子……11 小时前
记力扣42.接雨水 练习理解
笔记·学习·算法·leetcode·职场和发展
Sheep Shaun12 小时前
STL:string和vector
开发语言·数据结构·c++·算法·leetcode
YGGP14 小时前
【Golang】LeetCode 118. 杨辉三角
算法·leetcode
sin_hielo14 小时前
leetcode 2054(排序 + 单调栈,通用做法是 DP)
数据结构·算法·leetcode