本文總結一下 shell 查看日誌的腳本
首先在我們開發的過程中不管我們是做什麼開發,java也好數據庫也好都會在服務器上產生大量的日誌。這些如果日誌文件太大的話我們就會查看起來很困難。(想一想在幾萬行的日誌文件中找一個關鍵字是不是很難受)這時候雖然有查找的命令但是還是手工操作難免手滑。
這個腳本主要是
1 能夠按照我們要查找的關鍵字查找並給出上下文,打印在終端。
2 能夠設置上下文的步長(遞歸調用實現)
3 能夠按照要求答應第幾次出現關鍵字的位置(如果出現分隔停止馬上停止)
這裏舉個例子如果我們要查看的日誌是這樣的 關鍵字是 ‘hello’我們設置的步長是 10 要打印的是最後一次也就是最近一次打印的日誌 1 就會得到如下結果
Test.sh logfile keyword numstep looknum
這是我們的參數
$1 是日誌文件名(默認當前路徑)
$2 關鍵字名字
$3 步長
$4 最近出現的位置(使用遞歸實現)
如上圖我們最近一次出現 hello關鍵字是在85行我們設置步長是10的話得出的結果如下
如果要打印倒數第二次出現hello的位置的話
sh test.sh a.log hello 10 2 這裏把步長設置爲2
結果如果圖我們默認遇到 ########## 停止
代碼部分
#!/bin/sh
logfile=$1
keyword=$2
numstep=$3
looknum=$4
if [ $# -ne 4 ]
then
echo "格式錯誤,正確格式(test.sh logfile keyword numstep looknum) ! "
exit
fi
function look()
{
local up=0
local LOCAL_N=$1
local LOCAL_D=$2
local LOCAL_N_SUB_1=$(($LOCAL_N - 1))
if [ $LOCAL_N -eq 0 ]
then
#echo "輕鬆搞定"
return 0
else
numstep=`expr ${numstep}`
num=`grep -n "${keyword}" ${LOCAL_D}|tail -1|awk -F ":" '{print $1}'`
if [[ -z ${num} ]]
then
echo "文件中沒有關鍵字 '${keyword}'"
exit
fi
num=`expr ${num}`
if [ ${num} -le ${numstep} ]
then
startnum=1
else
startnum=`expr ${num} - ${numstep}`
fi
endnum=`expr ${num} + ${numstep}`
cat ${LOCAL_D} | sed -n "${startnum},${endnum}"p > /test/tmp.log
num=`grep -n "${keyword}" /test/tmp.log|tail -1|awk -F ":" '{print $1}'`
num=`expr ${num}`
test1=`sed -n "1,${num}"p /test/tmp.log | grep '######'`
if [ "$?" -eq "0" ]
then
start_finalnum=`sed -n "1,${num}"p /test/tmp.log | grep -n '######' | tail -1 | awk -F ":" '{print $1}'`
aaa=`sed -n "1,${num}"p /test/tmp.log | grep -n '######' | tail -1 | awk -F":" '{print $1}'`
up=1
else
start_finalnum=1
fi
test=`sed -n "${num},${endnum}"p /test/tmp.log | grep '######' `
if [ "$?" -eq "0" ]
then
end_finalnum=`sed -n "${num},${endnum}"p /test/tmp.log | grep -n '######' | head -1 | awk -F ":" '{print $1}'`
else
end_finalnum=`cat /test/tmp.log|wc -l`
fi
end_finalnum=`expr ${num} + ${end_finalnum} - 1`
#切出來log
if [ $up -eq 0 ]
then
marknum=${startnum}
else
marknum_tmp=`expr ${startnum} + ${aaa}`
marknum=`expr ${marknum_tmp} - 1`
fi
cat ${LOCAL_D} | sed -n "1,${marknum}"p > /test/datou_tmp.log
cp -rf datou_tmp.log datou.log
look $LOCAL_N_SUB_1 datou.log
fi
}
look $looknum $logfile
sed -n "${start_finalnum},${end_finalnum}"p /test/tmp.log
#echo"${start_finalnum}----${end_finalnum}-----${end_finalnum}"
#rm tmp.log
#rm datou.log
如果看不懂代碼的話,歡迎評論,我會寫的再詳細點。