标签:linux三剑客
Linux三剑客企业级经典面试题解答实战
说明:来自早晨老男孩教育在线班一期同学的面试题和学生给出的答案整理
面试题:请过滤oldboy.log中在device: {}里面出现了多少次oldboy,过滤并统计出来。
oldboy is a linuxer.
device: {
oo
oldboy
no sql
this is log
niu niu
}
oldboy
device: {
oldboy
no sql
this is log
niu niu
}
oldboy
device: {
oldboy
no sql
this is log
niu niu
}
device: {
oldboy
no sql
this is log
niu niu
}
解答:本题可利用sed和awk取区间的用法:
1)利用数字行数取区间
[oldboy@oldboy ~]$ seq 10 >test.log
[oldboy@oldboy ~]$ sed -n ‘2,5p‘ test.log
2
3
4
5
[oldboy@oldboy ~]$ awk ‘NR>1&&NR<6‘test.log
2
3
4
5
2)利用字符串匹配取区间
本题可以取以"device"开头以 "}"结尾,然后将里面的符合要求的字符串过滤计数就可以了。
取区间的方法:
sed -n ‘/^device/,/\}$/p‘ oldboy.log
awk ‘/device: {/, /}/‘ oldboy.log
提示:
sed -n ‘/区间开始标识/,/区间结束标识/p‘ oldboy.log
3)本题完整答案:这里给3个方法
sed -n ‘/^device/,/\}$/p‘ oldboy.log|grep -w"oldboy"|wc -l
awk ‘/device: {/, /}/‘ oldboy.log|grep -w oldboy|wc -l
awk ‘/device: {/,/}/ {if($0=="oldboy") count++}END{print count}‘ oldboy.log
演示:
[oldboy@oldboy ~]$ sed -n ‘/^device/,/\}$/p‘oldboy.log|grep -w "oldboy"|wc -l
4
[oldboy@oldboy ~]$ awk ‘/device: {/,/}/ {if($0=="oldboy")count++} END{print count}‘ oldboy.log
4
[oldboy@oldboy ~]$ awk ‘/device: {/, /}/‘ oldboy.log|grep-w oldboy|wc -l
4
4)考虑到面试题的企业里的通用性,即一行还可能有多个oldboy,即原题改为如下:
[oldboy@oldboy ~]$ cat oldboy.log
oldboy is a linuxer.
device: {
oo
oldboy oldboy oldboy
no sql
this is log
niu niu
}
oldboy
device: {
oldboy oldboy
no sql
this is log
niu niu
}
oldboy oldboy
device: {
oldboy oldboy
no sql
this is log
niu niu
}
device: {
oldboy oldboy
no sql
this is log
niu niu
}
oldboy
因此本题最佳答案,老男孩老师从学生的解答中选举优秀答案如下:
sed -n ‘/^device/,/\}$/p‘ oldboy.log|xargs -n 1|sort|grep-w oldboy|wc -l
awk ‘/device: {/, /}/‘ oldboy.log|grep -w oldboy|tr" " "\n"|wc -l
awk ‘/{/,/}/{a+=gsub("oldboy","")}END{print a}‘ oldboy.log
sed -n ‘/{/,/}/{/oldboy/p}‘ oldboy.log | tr ‘ ‘ ‘\n‘ | wc -l
演示:
[oldboy@oldboy ~]$ sed -n ‘/^device/,/\}$/p‘oldboy.log|xargs -n 1|sort|grep -w oldboy|wc -l
9
[oldboy@oldboy ~]$ awk ‘/device: {/, /}/‘ oldboy.log|grep-w oldboy|tr " " "\n"|wc -l
9
[root@littleboy ~]# awk ‘/{/, /}/{a+=gsub("oldboy","")}END{printa}‘ oldboy.log
9
[root@littleboy ~]# sed -n ‘/{/,/}/{/oldboy/p}‘oldboy.log|tr ‘ ‘ ‘\n‘| wc -l
9
普通人员可以就题论题,高手的解答多考虑通用性,高手和低手的差别就在于此!
本文出自老男孩教育的第三本书精品书籍,《跟老男孩学习Linux运维:精通linux三剑客》即将出版,敬请期待!
运维Q群 384467551 架构师Q群390642196
加群(务必标记来源)即可免费获得《linux三剑客实践》电子书一套!
学运维好工作,就选北京老男孩IT教育!
本文出自 “老男孩linux培训” 博客,请务必保留此出处http://oldboy.blog.51cto.com/2561410/1908510
标签:linux三剑客
原文地址:http://oldboy.blog.51cto.com/2561410/1908510