1

我的文件内容如下:

20 name:abc addr:203.45.247.247/255.255.255.255 WDW-THRESH:12 BW-OUT:10000000bps BW-IN:15000000bps STATSDEVICE:test247 STATS:Enabled (4447794/0) <IN OUT>
25 name:xyz160 addr:203.45.233.160/255.255.255.224 STATSDEVICE:test160 STATS:Enabled priority:pass-thru (1223803328/0) <IN OUT>
37 name:testgrp2 <B> WDW-THRESH:8 BW-BOTH:192000bps STATSDEVICE:econetgrp2 STATS:Enabled (0/0) <Group> START:NNNNNNN-255-0 STOP:NNNNNNN-255-0
62 name:blahblahl54 addr:203.45.225.54/255.255.255.255 WDW-THRESH:5 BWLINK:cbb256 BW-BOTH:256000bps STATSDEVICE:hellol54 STATS:Enabled (346918/77) <IN OUT>

使用以下 awk 脚本:

awk -F"[: ]" '{out=$1; for(i=2;i<=NF;i++)if($i~/bps/){sub("bps","",$i);out=out" "$i} print out;out=""}' input.txt

我得到了这个输出:

20 10000000 15000000
25
37 192000
62 256000

但我希望这个输出:

20  15000000 10000000
25
37 192000
62 256000
4

2 回答 2

4

反转循环

awk -F"[: ]" '{out=$1; for(i=NF;i >1;i--)if($i~/bps/){sub("bps","",$i);out=out" "$i} print out;out=""}' file.txt

无需在循环中检查 $0 和 $1。$0 是整行并且 $1 已经包含在输出中

于 2012-06-27T11:02:11.103 回答
0

也许“BW-IN”和“BW-OUT”并不总是以相同的顺序出现。

awk -F"[: ]" '
    {
        out = $1;
        for (i = 2; i <= NF; i++) {
            if ($i ~ /bps/) {
                sub("bps", "", $i);
                if (! flag) {
                    out = out " " $i save
                } else {
                    flag = 0
                    save = " " $i
                }
            }
            if ($i == "BW-OUT") {
                flag = 1
            }
        }
        print out;
        out = save = ""
    }
' input.txt
于 2012-06-27T11:29:09.650 回答