我该如何解析和转换ip数据库?

时间:2016-03-22 09:08:19

标签: bash awk

我有这样的ip database(ripe-apnic):

inetnum:      218.75.100.64 - 218.75.100.67
netname:      YONGKANG-SHIJI-NETBAR
country:      CN
descr:        Yongkang Shiji Internet Bar
descr:        NULL
admin-c:      XY203-AP
tech-c:       CJ54-AP
status:       ASSIGNED NON-PORTABLE
changed:      auto-dbm@dcb.hz.zj.cn 20040610
mnt-by:       MAINT-CN-CHINANET-ZJ-JH
source:       APNIC

inetnum:        218.75.99.0 - 218.75.99.3
netname:        WEISHENG-COLTD
country:        CN
descr:          Donggan Hospital
descr:
admin-c:        DS1202-AP
tech-c:         CJ54-AP
mnt-irt:        IRT-CHINANET-ZJ
status:         ASSIGNED NON-PORTABLE
changed:        zjnoc_ip_5@163.com 20150510
mnt-by:         MAINT-CN-CHINANET-ZJ-JH
source:         APNIC
...

我需要像这样转换为csv文件(只是ipstart-ipend-netname-country-descr1-source):

218.75.100.64;218.75.100.67;YONGKANG-SHIJI-NETBAR;CN;Yongkang Shiji Internet Bar;APNIC
218.75.99.0;218.75.99.3;WEISHENG-COLTD;CN;Donggan Hospital;APNIC
...

如何使用awk或bash执行此操作?

1 个答案:

答案 0 :(得分:2)

使用awk你可以这样做:

awk -F ':[[:blank:]]*' '/inetnum:/{ip=$2; sub(/ +- +/, ";", ip)} /netname:/{nn=$2}
   /country:/{ct=$2} ds=="" && /descr:/{ds=$2}
  /source:/{print ip, nn, ct, ds, $2; ds=""}' OFS=";" file

<强>输出:

218.75.100.64;218.75.100.67;YONGKANG-SHIJI-NETBAR;CN;Yongkang Shiji Internet Bar;APNIC
218.75.99.0;218.75.99.3;WEISHENG-COLTD;CN;Donggan Hospital;APNIC

这将忽略第二个descr字段。