简体   繁体   English

使用正则表达式过滤apache日志文件

[英]Filter apache log file using regular expression

I have a big apache log file and I need to filter that and leave only (in a new file) the log from a certain IP: 192.168.1.102 我有一个很大的apache日志文件,我需要对其进行过滤,仅将某个IP:192.168.1.102的日志保留在新文件中。

I try using this command: 我尝试使用以下命令:

sed -e "/^192.168.1.102/d" < input.txt > output.txt

But "/d" removes those entries, and I needt to leave them. 但是“ / d”删除了那些条目,我不需要离开它们。

Thanks. 谢谢。

What about using grep ? 使用grep呢?

cat input.txt | grep -e "^192.168.1.102" > output.txt

EDIT: As noted in the comments below, escaping the dots in the regex is necessary to make it correct. 编辑:如下面的注释中所述,转义正则表达式中的点对于使其正确是必要的。 Escaping in the regex is done with backslashes: 用反斜杠转义正则表达式:

cat input.txt | grep -e "^192\.168\.1\.102" > output.txt

sed -n 's/^192\\.168\\.1\\.102/&/p'

sed比我的机器上的grep快

I think using grep is the best solution but if you want to use sed you can do it like this: 我认为使用grep是最好的解决方案,但是如果您想使用sed,您可以这样做:

sed -e '/^192\.168\.1\.102/b' -e 'd'

The b command will skip all following commands if the regex matches and the d command will thus delete the lines for which the regex did not match. 如果正则表达式匹配,则b命令将跳过所有后续命令,因此d命令将删除正则表达式不匹配的行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM