我必须从任何应用程序日志中提取特定日期的日志。我们一般做什么
我制作了小脚本,但我认为我的逻辑不正确:
#!/bin/bash
read -p " enter the App name" : app
read =p " enter the Date in this Format 10 Jan 20:01:00" : date
FILE=/logs/$app.log
# Check if $app exists or not
if test ! -f "$app" /logs
then
echo "Error - $app not found."
else
First_line=$(cat $FILE | grep $date | .=)
Second_line=$(tail -1 $FILE | .=)
vi $FILE | $First_line, $Second_line w $app.txt
fi
答案 0 :(得分:1)
行
中有错误if test ! -f "$app" /logs
你分开了#34; $ app"和/有空格的日志; test -f
需要一个参数,因此应该是:
if test ! -f "$app"/logs
要从给定日期开始到日志文件的当前结束,您应该使用sed
(意思是"流编辑器"),这是为非文件的非交互式编辑而设计的:
sed -n '/'$date'/,$ p' $app.log >$app.txt
参数-n
仅用于输出匹配的内容,而不是整个文件。
这里我告诉sed
提取两个正则表达式之间的所有内容,第一个是给定的$date
参数,第二个是#34;文件结尾"。您可以轻松更改此内容以提取特定日期或其他任何日志。
由于某些事情似乎不清楚,我正在添加一个完整的例子:
我有一个apache日志文件,其中记录的日期类似于[01/Apr/2015:22:31:21 +0200]
。
所以我能做到:
export date="01\/Apr\/2015"
重要的是要注意我正在逃避这里的斜线,因为它们正在进入正则表达式。这必须在正则表达式中具有一些特殊含义的所有内容中完成。
然后我可以做:
sed -n '/'$date'/,$ p' myaccess.log
我将4月1日的所有内容记录下来,直到文件结束。
答案 1 :(得分:0)
如果您的任务与您描述的一样机械,您可以使用here文档从脚本向vi
传递命令。
我正在谈论类似这样的事情
#!/bin/bash
read -p " enter the App name" : app
read =p " enter the Date in this Format 10 Jan 20:01:00" : date
FILE=/logs/$app.log
# Check if $app exists or not
if test ! -f "$app" /logs
then
echo "Error - $app not found."
else
vi $FILE <<-_EOF_
/date
.=
G
first_line,Last_line w filname.log
etc, etc
_EOF_
fi
我刚刚写了这个想法,你很想找到乐趣去探索。我知道代码不起作用。
答案 2 :(得分:0)
我使用awk:
awk -v date="$date" '$0 ~ date {p=1} p' file.in > file.out
这将在首次看到日期时开始打印行,直到行结束。