我试图在两个给定日期提取日志。如果我指定像4月02日15:21:28这样的日期代码工作正常,我的意思是如果知道精确的分钟和秒的时间,但代码失败,我传递这样的值 从4月02日15 *到4月4日15 *这里15小时,实际上我想制作一个脚本,用户只需要添加日期和时间(只有几小时没有分钟或秒)
> #!/bin/bash
read -p " enter the App name : " app
file="/logs/$app/$app.log"
read -p " Enter the Date in this Format --'10 Jan 20 or Jan 10 20' : " first
read -p " Enter the End time of logs : " end
if [ -f "$file" ]
then
if grep -q "$first" "$file"; then
final_first=$first
fi
if grep -q "$end" "$file"; then
final_end=$end
fi
sed -n " /$final_first/,/$final_end/ "p $file >$app.txt
else
echo "$app.log not found, Please check correct log name in deployer"
fi
示例数据:
Apr 07 12:39:15 DEBUG [http-0.0.0.0-8089-21] model.DSSAuthorizationModel - pathInfo : /about-ses
Apr 07 12:39:15 DEBUG [http-0.0.0.0-8089-21] servlet.CasperServlet - Request about to be serviced by model: com.ge.oilandgas.sts.model.SessionValidModel
答案 0 :(得分:0)
我使用的语言具有内置日期时间解析或易于包含的模块。例如,perl
first="Apr 07 12"
end="Apr 08 00"
perl -MTime::Piece -sane '
BEGIN {
$first_ts = Time::Piece->strptime($first, "%b %d %H")->epoch;
$end_ts = Time::Piece->strptime($end, "%b %d %H")->epoch;
}
$ts = Time::Piece->strptime(join(" ", @F[0..2]), "%b %d %T")->epoch;
print if $first_ts <= $ts and $ts <= $end_ts;
' -- -first="$first" -end="$end" <<END
Apr 07 11:39:15 DEBUG [http-0.0.0.0-8089-21] model.DSSAuthorizationModel - pathInfo : /about-ses
Apr 07 12:00:00 DEBUG [http-0.0.0.0-8089-21] model.DSSAuthorizationModel - pathInfo : /about-ses
Apr 07 12:39:15 DEBUG [http-0.0.0.0-8089-21] model.DSSAuthorizationModel - pathInfo : /about-ses
Apr 07 12:39:15 DEBUG [http-0.0.0.0-8089-21] servlet.CasperServlet - Request about to be serviced by model: com.ge.oilandgas.sts.model.SessionValidModel
Apr 07 23:59:59 DEBUG [http-0.0.0.0-8089-21] servlet.CasperServlet - Request about to be serviced by model: com.ge.oilandgas.sts.model.SessionValidModel
Apr 08 00:00:01 DEBUG [http-0.0.0.0-8089-21] servlet.CasperServlet - Request about to be serviced by model: com.ge.oilandgas.sts.model.SessionValidModel
END
输出
Apr 07 12:00:00 DEBUG [http-0.0.0.0-8089-21] model.DSSAuthorizationModel - pathInfo : /about-ses
Apr 07 12:39:15 DEBUG [http-0.0.0.0-8089-21] model.DSSAuthorizationModel - pathInfo : /about-ses
Apr 07 12:39:15 DEBUG [http-0.0.0.0-8089-21] servlet.CasperServlet - Request about to be serviced by model: com.ge.oilandgas.sts.model.SessionValidModel
Apr 07 23:59:59 DEBUG [http-0.0.0.0-8089-21] servlet.CasperServlet - Request about to be serviced by model: com.ge.oilandgas.sts.model.SessionValidModel
鉴于您的代码,我会做出以下更改:
if ! [ -f "$file" ]; then
echo "$app.log not found, Please check correct log name in deployer"
exit 1
fi
grep -q "$first" "$file" && final_first="/$first/" || final_first='1'
grep -q "$end" "$file" && final_end="/$end/" || final_end='$'
sed -n "${final_first},${final_end}p" "$file" >"$app.txt"
为sed范围,第一行和最后一行提供默认地址。