原始文件格式:
Nov 12 19:56:52 libra kernel: [ 1353.27355] WarningIN=em0 OUT=eth0 MAC=c8:1b:3c:fd:5D:e9:90:a9:8F:43:83:E3:15:0e SRC=222.171.89.16 DST=49.137.111.136 LEN=222 TOS=0x8C PREC=0xbF TTL=107 ID=31469 PROTO=ICMP TYPE=35 CODE=8 ID=24917 SEQ=166
Aug 00 08:35:51 virgo kernel: [ 4584.5613] That's oddIN=em0 OUT=eth0 MAC=0a:09:AA:4F:6C:41:c6:De:D6:6f:83:41:8e:dC SRC=142.53.155.238 DST=252.1.134.24 LEN=506 TOS=0x11 PREC=0x5c TTL=67 ID=5098 PROTO=ICMP TYPE=35 CODE=5 ID=31329 SEQ=22
Jun 21 11:47:48 taurus kernel: [ 741.5237] Look into this IN=em1 OUT=eth0 MAC=Bd:5b:ab:b7:47:fA:df:53:0E:E8:A7:2a:f6:c6 SRC=50.219.1.59 DST=56.95.45.60 LEN=390 TOS=0xf2 PREC=0x79 TTL=122 ID=28867 PROTO=UDP SPT=16351 DPT=15354 LEN=9
后:
19:56:52 12 Nov;Warning;em0;eth0;222.171.89.16;49.137.111.136;ICMP;;
08:35:51 00 Aug;That's odd;em0;eth0;142.53.155.238;252.1.134.24;ICMP;;
11:47:48 21 Jun;Look into this ;em1;eth0;50.219.1.59;56.95.45.60;UDP;16351;15354
答案1
干得好
awk '{ if (NF > 0)
{printf $3 " " $2 " " $1 ";"}
{for (idex=8; idex <= NF; idex++)
{ printf $idex " " } {print}}}' <FILE> \
\
| sed -r 's/IN=/;/ ; s/\sOUT=/;/ ; s/ MAC.*\sSRC=/;/ ; s/ DST=/;/ ; s/ LEN.*PROTO=/;/ ; s/ SPT=/;/ ; s/ DPT=/;/ ; s/(LEN=[0-9]*|TYPE=[0-9]*|CODE=[0-9]*|ID=[0-9]*|SEQ=[0-9]*)//g ; s/\s*$/;;/ ; s/^;;$//'
确保将其替换<FILE>
为您要处理的文件的名称。
希望它有效——对我来说效果很好。
答案2
sed -r 's/([^ ]+) ([^ ]+) ([^ ]+) [^]]+\] (.+)IN=([^ ]+) OUT=([^ ]+)* .*SRC=([^ ]+) DST=([^ ]+) .*PROTO=(.*)/\3 \2 \1;\4;\5;\6;\7;\8;\9;/' file|sed -r 's/(([^;]*;){6})([^ ]+) (SPT=)*([0-9]+ )*(DPT=)*([0-9]+)*.*/\1\3;\5;\7/'
答案3
你能这样做sed
,例如建议@Hero。更好的问题是你是否应该。sed
很棒,它非常强大,但它并不总是最好的工具。我发现用 Perl 做这种事情要容易得多:
perl -ne 's/(...)\s*(\d+)\s*([\d:]+).+?\]\s*.*?IN=(.+?)\s.*OUT=(.+?)\s.*SRC=([\d\.]+).*DST=([\d\.]+)/$3 $2 $1;$4;$5;$6;$7;$8/;print' foo.txt