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}'
相关推荐
柒号华仔1 小时前
「速通Shell」聚砖成墙,Shell函数封装之道
linux·ssh·bash
evans在进步2 小时前
LeetCode 394:字符串解码——Java 单栈模拟与嵌套解析详解
java·python·leetcode
Nil2083 小时前
leetcode 189轮转数组
数据结构·算法·leetcode
吃着火锅x唱着歌3 小时前
LeetCode 3885.设计事件管理器
算法·leetcode·职场和发展
土司大王4 小时前
LeetCode hto100——字母异位词分组
java·算法·leetcode
土司大王5 小时前
LeetCode hot100——两数之和
数据结构·算法·leetcode
Navigator_Z5 小时前
LeetCode //C - 1200. Minimum Absolute Difference
c语言·算法·leetcode
wabs6666 小时前
关于字符串【力扣344.反转字符串的思考】
数据结构·算法·leetcode
Nil2087 小时前
leetcode 73矩阵置0
算法·leetcode·矩阵
旖旎夜光9 小时前
LeetCode 1658:将 x 减到 0 的最小操作数(滑动窗口) —— 题解
数据结构·c++·算法·leetcode·滑动窗口