LeetCode上稀缺的四道shell编程题解析

tech2022-09-07  114

LeetCode 192

 

01

题目描述

写一个 bash 脚本以统计一个文本文件 words.txt 中每个单词出现的频率。为了简单起见,你可以假设:

1. words.txt只包括小写字母和 ' ' 。 

2. 每个单词只由小写字母组成。 

3. 单词间由一个或多个空格字符分隔。

 

02

(words.txt)文件内容

 

the day is sunny the thethe sunny is is

 

03

输出(以词频降序排列):

the 4is 3sunny 2day 1

 

04

解析

 

对于words.txt文件进行词频统计,首先要做的事情就是把words.txt文件当中的每一个单词分割出来,分割出每一个单词可以使用以下两种方式:

 

使用awk命令:

[root@localhost ~]# awk '{for(i=1;i<=NF;i++){print $i}}' words.txt  the day is sunny the the the sunny is is

其中NF表示当前记录的字段数(即列数)

$i 文件中每行以间隔符号分割的

最新回复(0)