2017年最新企业面试题之shell(三)
练习题1:写一个shell脚本,类似于日志切割,系统有个logrotate程序,可以完成归档。但现在我们要自己写一个shell脚本实现归档。
举例: 假如服务的输出日志是1.log,我要求每天归档一个,1.log第二天就变成1.log.1,第三天1.log.2, 第四天 1.log.3 一直到1.log.5
脚本内容如下:
#!/bin/sh function logdir () { [ -f $1 ] && rm -f $1 } for i in $(seq 5 -1 2) do q=$[$i-1] logdir /data/1.log.$i if [ -f /data/1.log.$q ] then mv /data/1.log.$q /data/1.log.$i fi done logdir /data/1.log.1 mv /data/1.log /data/1.log.1
练习题2:打印只有一个数字的行
如题,把一个文本文档中只有一个数字的行给打印出来。
参考答案如下:
[root@ceshiji ~]# cat 2017-8-31.txt My name is wtf I love zd qqqqqqqqqqqqqqqqq aaaaaaaaaaaaaaaaa rrrrrrrrrr1tttttttttttttt yyyyyyyyyy3333ssssssssssss 4444444444444444444444444 4SRDTYGFJ 5 333
脚本如下:
#!/bin/bash file=/root/2017-8-31.txt line=$(wc -l $file|awk '{print $1}') for i in $(seq 1 $line) do q=`sed -n "$i"p $file|grep -o '[0-9]'|wc -l` if [ $q -eq 1 ];then sed -n "$i"p $file fi done
脚本运行结果:
rrrrrrrrrr1tttttttttttttt
4SRDTYGFJ
5
说明:
(1)grep -o 其中 -o 表示“only-matching”,即“仅匹配”之意,详细内容参考:http://blog.csdn.net/u013982161/article/details/52334940
(2)提取数字:wc -l $file|awk '{print $1}'
解释如下:
[root@ceshiji ~]# wc -l 2017-8-31.txt 10 2017-8-31.txt [root@ceshiji ~]# wc -l 2017-8-31.txt |awk '{print $1}' 10
转载于:https://blog.51cto.com/wutengfei/1961513