我有一个像这样的行文件
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
我想使用awk找到包含我正在寻找的地址的行并重新排列它。
我的尝试是
awk '/222.171.89.16/ {print $2,$3,$6,$4,$5,$1}' logs
那只是给了我一行,因为我觉得awk需要被告知如何分离字符串所以,我尝试使用FS
awk '/222.171.89.16/ {FS = ";"}; {print $2,$3,$6,$4,$5,$1}' logs
但这只适用于某些行。此外,我想在开头说,如果IP地址来自第5列,它是出站的,如果它来自第6列,它是入站的。所以数据应按此顺序排列。请原谅我将要做的事情。
TYPE | IFACE | OFACE | PROT | SPORT | DPORT | DATE |
|------+---------+---------+------+-------+-------+-----------------|
| OUT | em0 | eth0 | ICMP | 0 | 0 | 08:35:51 00 Aug |
| OUT | | virbr0 | TCP | 24760 | 26014 | 07:08:48 18 Feb |
| IN | em2 | | ICMP | 0 | 0 | 21:54:43 06 Aug |
| OUT | virbr0 | | UDP | 29450 | 2501 | 00:46:27 04 Aug |
| IN | virbr0 | eth1 | ICMP | 0 | 0 | 06:29:02 20 Sep |
| IN | em0 | em0 | ICMP | 0 | 0 | 15:41:37 09 Nov |
| OUT | eth0 | virbr0 | UDP | 21879 | 3645 | 13:43:33 11 Nov |
| IN | em1 | em1 | UDP | 7699 | 18698 | 06:06:15 12 Oct |
| OUT | em1 | em0 | ICMP | 0 | 0 | 14:11:09 25 Aug |
| IN | em2 | em0 | UDP | 24814 | 31182 | 17:45:57 00 Dec |
| OUT | eth1 | em1 | UDP | 4915 | 18665 | 01:49:46 15 Oct |
---------------------------------------------------------------------
答案 0 :(得分:1)
设置FS是正确的(默认为空格字符,但您需要';')
如果您正在寻找IP地址,您的正则表达式应该掩盖点。
/222\.171\.89\.16/ .....
如果你想区分你可以写的字段位置(而不是reg。表达式)
$5=="222.171.89.16" { print ....}
以匹配outbounds的标准
答案 1 :(得分:1)
通常,通过-F开关或BEGIN子句定义FS(如下所示)。我的sample.awk没有生成完整的输出,但我想你可以把它当作一个起点。
$ awk -v IP=222.171.89.16 -f sample.awk yourfile
|OUT |em0 |eth0 |19:56:52 12 Nov|
$ cat sample.awk
BEGIN {
FS = ";" # Field separator
fmt = "|%-5s|%-5s|%-5s|%-15s|\n" # Output format
if (! IP) { # Check if an IP address has been provided
print "No IP address given! Exiting." > "/dev/stderr"
exit 1
}
}
# Test records and print formatted output
$0 ~ IP {
TYPE = $5 == IP ? "OUT" : "IN"
printf fmt, TYPE, $3, $4, $1
}