#!/bin/bash
echo 示例用法1:./log_truncate.sh 18/Sep/2017 20/Sep/2017 access_zl.log"(截取指定日期之间的日志记录,日期请不要跨月)"
echo 示例用法2:./log_truncate.sh 18/Sep/2017 10:13:06 18/Sep/2017 14:15:08 access_zl.log"(截取指定时间内的日志记录,日期请不要跨月)"
count=$# #参数个数
first_day=`echo $1|cut -d / -f 1`
var=$1
month=${var#*/}
#echo $count
#echo $first_day
#echo $second_day
#echo $month
rm logtruncatebytime.text -rf
if [ $count -eq 3 ];then
second_day=`echo $2|cut -d / -f 1`
int=$first_day
#echo $int
while(( $int<=$second_day ))
do
str=$int"/"$month
#echo $str
cat $3|grep $str>>"logtruncatebytime.text"
let "int++"
done
elif [ $count -eq 5 ];then
begin_str=$1":"$2
#echo $begin_str
end_str=$3":"$4
#echo $end_str
begin_line=$(cat $5|grep -n $begin_str|awk -F ':' '{print $1}'|head -n1)
#echo beginstr=$begin_str begin_line=$begin_line
end_line=$(cat $5|grep -n $end_str|awk -F ':' '{print $1}'|tail -n1)
#echo end_str=$end_str end_line=$end_line
if [ -z "$begin_line" ];then
echo "你输入的开始时间不存在,请重新输入!"
exit
elif [ -z "$end_line" ];then
echo "输入的结束时间不存在,请重新输入!"
exit
fi
cat $5 |head -n $end_line|tail -n +$begin_line >>"logtruncatebytime.text"
else
echo "输入格式错误,请重新按照示例用法输入!"
exit
fi
zip -r logtruncatebytime.zip logtruncatebytime.text
if [ -f "./logtruncatebytime.zip" ];then
echo $(cat logtruncatebytime.text|wc -l) 条记录已经写入到logtruncatebytime.zip文件中......
rm logtruncatebytime.text -rf
else
echo "程序执行失败,请重新检查输入再执行......"
fi