「脚本」词频统计 & 有效电话号码

2020-01-14  本文已影响0人  林昀熙

00192 词频统计

题目描述

写一个 bash 脚本以统计一个文本文件 words.txt 中每个单词出现的频率。

为了简单起见,你可以假设:

示例:

假设 words.txt 内容如下:

the day is sunny the the
the sunny is is

你的脚本应当输出(以词频降序排列):

the 4
is 3
sunny 2
day 1

说明:

不要担心词频相同的单词的排序问题,每个单词出现的频率都是唯一的。
你可以使用一行 Unix pipes 实现吗?

力扣地址

解题报告

[root@localhost ~ ]$ cat words.txt | tr ' ' '\n'
the
day
is
sunny
the
the
the
sunny
is
is
[root@localhost ~ ]$ cat words.txt | tr ' ' '\n' | sort   
day
is
is
is
sunny
sunny
the
the
the
the
[root@localhost ~ ]$ cat words.txt | tr ' ' '\n' | sort | uniq -c
   1 day
   3 is
   2 sunny
   4 the
[root@localhost ~ ]$ cat words.txt | tr ' ' '\n' | sort | uniq -c | sort -r
   4 the
   3 is
   2 sunny
   1 day
[root@localhost ~ ]$ cat words.txt | tr ' ' '\n' | sort | uniq -c | sort -r | awk '{print $2, $1}'
the 4
is 3
sunny 2
day 1

最终答案

本题解由微信公众号小猿刷题提供, 错误之处, 欢迎指正.

cat words.txt | tr ' ' '\n' | sort | uniq -c | sort -r | awk '{print $2, $1}'
小猿刷题

00193 有效电话号码

题目描述

给定一个包含电话号码列表(一行一个电话号码)的文本文件 file.txt,写一个 bash 脚本输出所有有效的电话号码。

你可以假设一个有效的电话号码必须满足以下两种格式: (xxx) xxx-xxxx 或 xxx-xxx-xxxx。(x 表示一个数字)

你也可以假设每行前后没有多余的空格字符。

示例:

假设 file.txt 内容如下:

987-123-4567
123 456 7890
(123) 456-7890

你的脚本应当输出下列有效的电话号码:

987-123-4567
(123) 456-7890

力扣地址

解题报告

本题主要是如何去体现电话号码的正则表达式:

转换成正则表达式

^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$
基于awk统计

本题解由微信公众号小猿刷题提供, 错误之处, 欢迎指正.

[root@localhost ~ ]$ awk '/^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$/' file.txt
987-123-4567
(123) 456-7890

基于grep统计

本题解由微信公众号小猿刷题提供, 错误之处, 欢迎指正.

[root@localhost ~ ]$ grep -e '^\([0-9]\{3\}-\|([0-9]\{3\}) \)[0-9]\{3\}-[0-9]\{4\}$' file.txt 
987-123-4567
(123) 456-7890
小猿刷题
上一篇 下一篇

猜你喜欢

热点阅读