leetcode shell题目题解

来源:互联网 发布:java转嵌入式 编辑:程序博客网 时间:2024/06/08 12:04

学习了一段时间的shell脚本,平常能查查资料写一些,今天发现了leetcode上除了算法还有shell问题,共有四道,有的也是参考了答案,哈哈,下面是题解了:

Easy部分:
195. Tenth Line
Your script should output the tenth line
要求:打印出文件内容的第十行

错误解法:cat ./file.txt | head -n 10 | tail -n 1注释: 想要head打印前10行,tail选择最后一行。错误之处在于没考虑到文件如果没有10行,则会把文件最后一行输出而非输出 空正确解法1:cat ./file.txt | tail -n+10 | head -n 1注释:tail -n+(M+1)打印第M行以后所有行,在打印head第一行即可正确解法2:cat ./file.txt | awk 'NR==10'正确解法3:sed -n 10p ./file.txt

-193. Valid Phone Numbers
You may assume that a valid phone number must appear in one of the following two formats: (xxx) xxx-xxxx or xxx-xxx-xxxx. (x means a digit)
要求: 筛选出 123-123-1234 或者 (123) 123-1234 格式的电话号码
考察: 正则表达式中”数字”和”或”

解法1:grep -P '(^\d{3}-|^\(\d{3}\) )\d{3}-\d{4}$' ./file.txt解法2:grep -e '(^[0-9]{3}-|^\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$' ./file.txt注释: -e参数可扩展的正则表达式,只支持基本正则 例如:[0-9] [a-Z]等等解法3:awk "/^([0-9]{3}-|\([0-9]{3}\) )[0-9]{3}-[0-9]{4}$/" ./file.txt注释: awk正则使用形如 awk '/xxxxx/'

Medium部分:
194. Transpose File
For example, if file.txt has the following content:输入内容
name age
alice 21
ryan 30

Output the following:要求输出
name alice ryan
age 21 30

cat file.txt |awk '{    #每行都会awk 执行    for (i = 1; i <= NF; i++) {        if(NR == 1) {            s[i] = $i;        } else {        #按照NF 长度建立数组,每个NF 保存对应部分 $i            s[i] = s[i] " " $i;        }    }}END {    #END 执行仅一次    for (i = 1; s[i] != ""; i++) {        print s[i];    }}' 注释: 1.其中s数组格式形如s[1]="name alice ryan"s[2]="age 21 30"数组、字典的使用实例可以看看我的上一篇shell文章[shell 数组、字典、source、split简单实例](http://blog.csdn.net/u014297722/article/details/54601660)2.NF 字段filed序号 NR 行数序号  这是awk特有的两个变量

-192. Word Frequency
Write a bash script to calculate the frequency of each word in a text file words.txt.
words.txt contains only lowercase characters and space ’ ’ characters.
要求:统计文章内容单词词频;所有单词均是小写,单词之前以空格分割;词频由高到低输出排序
例如:
the 4
is 3
sunny 2
day 1

grep -e '[a-z]*' ./words.txt -o | sort | uniq -c | sort -nrk 1 | awk '{print $2" "$1;}'注释:1.grep -e筛选单词,-o输出所匹配到的2.sort 排序单词,在uniq命令前提是排序内容3.uniq -c 去掉重复的单词(得到group),输出 "出现次数 单词"形式;-c 是count4.sort 排序 -n按照数字排序 -r 倒序排序 -k指定排序的字段field即第一列5.awk 默认定界符为空格输出 $2 $1 即形如"单词 出现次数"格式
0 0