Grep 并打印回参考 [英] Grep and print back reference

查看:9
本文介绍了Grep 并打印回参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个 iptable 日志:

I have this iptable log:

Feb 25 10:32:48 XXX: [414645.555838] FW: DEN TCP IN=eth0 OUT= MAC=XYZ SRC=1.1.1.1 DST=2.2.2.2 LEN=40 TOS=0x00 PREC=0x00 TTL=57 ID=0 DF PROTO=TCP SPT=80 DPT=51814 WINDOW=0 RES=0x00 RST URGP=0

我想 grep 1.1.1.1 和 80(SRC 和 SPT 字段).我这样做:

I want to grep 1.1.1.1 and 80 (SRC and SPT field). I do this:

grep -oP 'SRC=([^ ]+).+SPT=([0-9]+)' /var/log/iptables.log

但它返回:

SRC=1.1.1.1 DST=2.2.2.2 LEN=40 TOS=0x00 PREC=0x00 TTL=57 ID=0 DF PROTO=TCP SPT=80

如何只获得 $1 和 $2(参考匹配值)?

How do I get $1 and $2 only ( reference to the matched value)?

推荐答案

sed 方法:

sed -rn 's/.*SRC=([^ ]+).*SPT=([0-9]+).*/1 2/p' /var/log/iptables.log

您可以在脚本或类似内容中读取 src spt 时将其通过管道传输到 .现在这当然不是很有效,因为模式中的三颗星,所以如果性能有问题,你可以考虑使用诸如cut之类的东西来提取某些字段:

You can pipe it to while read src spt in your script or something similar. Now this of course is not very efficient, because of three stars in the pattern, so if performance is an issue, you can consider using things like cut to extract certain fields:

cut -d' ' -f12,21 /var/log/iptables.log

不确定日志格式是否足够一致以使其正常工作.

Not sure if the log format is consistent enough for this to work.

这篇关于Grep 并打印回参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆