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}'
相关推荐
IMPYLH6 小时前
Linux 的 pinky 命令
linux·运维·服务器·bash
鹿角片ljp7 小时前
最长回文子串(LeetCode 5)详解
算法·leetcode·职场和发展
故事和你9113 小时前
洛谷-算法1-7-搜索2
数据结构·c++·算法·leetcode·深度优先·动态规划·图论
YuanDaima204814 小时前
双指针基础原理与题目说明
数据结构·人工智能·python·算法·leetcode·手撕代码
.柒宇.16 小时前
力扣hot100之最大子数组和(Java版)
数据结构·算法·leetcode
6Hzlia16 小时前
【Hot 100 刷题计划】 LeetCode 131. 分割回文串 | C++ 回溯算法基础切割法
c++·算法·leetcode
美式请加冰16 小时前
子序列问题
数据结构·算法·leetcode
6Hzlia17 小时前
【Hot 100 刷题计划】 LeetCode 1143. 最长公共子序列 | C++ 二维DP 与 哨兵技巧
c++·算法·leetcode
饕餮争锋18 小时前
Bash 简介
开发语言·bash
Soari18 小时前
Ziggo-CaaS-Switch软件配置教程
bash·powershell·tsn 交换机