0
点赞
收藏
分享

微信扫一扫

Jenkins教程-9-发送企业微信测试报告通知

sin信仰 2024-07-01 阅读 26
leetcodebash

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:

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:
cat words.txt | tr -s ' ' '\n' | sort | uniq -c | sort -nr | awk '{print $2, $1}'
举报

相关推荐

0 条评论