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}'
相关推荐
且听风吟ayan2 小时前
leetcode day19 844+977
leetcode·c#
MiyamiKK572 小时前
leetcode_位运算 190.颠倒二进制位
python·算法·leetcode
C137的本贾尼2 小时前
解决 LeetCode 串联所有单词的子串问题
算法·leetcode·c#
Joyner20183 小时前
python-leetcode-找到字符串中所有字母异位词
算法·leetcode·职场和发展
ll7788113 小时前
LeetCode每日精进:225.用队列实现栈
c语言·开发语言·数据结构·算法·leetcode·职场和发展
不想编程小谭8 小时前
力扣LeetCode: 931 下降路径最小和
数据结构·c++·算法·leetcode·动态规划
Helene19008 小时前
Leetcode 224-基本计算器
算法·leetcode·职场和发展
Luo_LA9 小时前
【LeetCode Hot100 矩阵】矩阵置零、螺旋矩阵、旋转图像、搜索二维矩阵II
数据结构·算法·leetcode·矩阵
卫胡迪9 小时前
Linux应用之构建命令行解释器(bash进程)
linux·运维·bash
取啥都被占用9 小时前
bash+crontab充当半个守护进程的歪招
bash·pgrep