2017年最新企業面試題之shell(三)
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:打印只有一個數字的行
如題,把一個文本文檔中只有一個數字的行給打印出來。
參考答案如下:
[[email protected] ~]# 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}‘
解釋如下:
[[email protected] ~]# wc -l 2017-8-31.txt
10 2017-8-31.txt
[[email protected] ~]# wc -l 2017-8-31.txt |awk ‘{print $1}‘
10
本文出自 “聖騎士控魔之手” 博客,請務必保留此出處http://wutengfei.blog.51cto.com/10942117/1961513
2017年最新企業面試題之shell(三)