awk分段处理记录并格式化输出(处理LDAP文件和DHCP记录)

王朝other·作者佚名  2008-05-18
窄屏简体版  字體: |||超大  

awk功能真是强大!可用来分段处理记录(即要处理的数据一段一段的),把记录中指定的部分取出并重新格式化输出 ...

=======================================

例子1. 分析LDAP记录(ldif格式的记录文本)

=======================================

现在有这样一笔记录,分段形式的,即:记录与记录之间以空行分割,如下:

uid: test

cn: test

sn: test user

o: people

mail: test@example.com

status: enabled

quota: 100

domain: example.com

uid: alice

cn: Alice

sn: alice user

o: people

mail: alice@example.com

status: enabled

quota: 200

domain: example.com

uid: bob

cn: boby

sn: bob user

o: people

mail: bob@example.com

status: enabled

quota: 300

domain: example.com

现在想取出上述记录中的某些字段,比如uid,cn,mail,quota,并且每个记录以一行的方式输出,脚本:

# awk -F ': ' '{if(/^uid|^cn|^mail|^quota/) {ORS=" "; print };

if(/^$/){ORS=" "; print ""}

}' data.ldif

输出结果:

test test test@example.com 100

alice Alice alice@example.com 200

bob boby bob@example.com 300

脚本说明:

awk处理时,默认将一行视为一个记录,但这里我们需要的是每一段为一个记录,由于段于段之间是以空行分割的,所以在没有遇到空行时,修改ORS为空格,表示同一个记录的不同部分;遇到空行时,修改ORS为换行,表示这个记录已经完了,这样就达到了我们的要求。

ORS意为 Output Record Seperator,即输出记录分割符,默认ORS为换行( )。

=======================================

例子2. 分析DHCP的lease记录(dhcpd.leases)

=======================================

lease 192.168.1.200 {

starts 2 2005/12/06 06:14:04;

ends 2 2005/12/06 18:14:04;

tstp 2 2005/12/06 18:14:04;

binding state free;

hardware ethernet 00:11:5b:15:61:e8;

uid "010021[25a350";

}

lease 192.168.1.197 {

starts 2 2005/12/06 06:41:01;

ends 2 2005/12/06 18:41:01;

tstp 2 2005/12/06 18:41:01;

binding state free;

hardware ethernet 00:0a:eb:12:71:3b;

uid "01001235322q;";

}

lease 192.168.1.191 {

starts 3 2005/12/07 01:31:19;

ends 3 2005/12/07 01:33:19;

tstp 3 2005/12/07 01:33:19;

binding state free;

hardware ethernet 00:0c:29:09:52:d8;

uid "010014)11R330";

}

lease 192.168.1.195 {

starts 3 2005/12/07 01:31:20;

ends 3 2005/12/07 13:31:20;

tstp 3 2005/12/07 13:31:20;

binding state active;

next binding state free;

hardware ethernet 00:0c:29:09:52:d8;

uid "010014)11R330";

}

lease 192.168.1.194 {

starts 3 2005/12/07 01:50:20;

ends 3 2005/12/07 13:50:20;

tstp 3 2005/12/07 13:50:20;

binding state active;

next binding state free;

hardware ethernet 00:e0:4c:c9:86:56;

}

现在要查看当前活动的租约记录(已分配的IP/起始时间/过期时间/目标机器的MAC地址),脚本:

cat dhcpd.leases|grep -v ^#|awk

'{if(/^lease|^ binding|^ starts|^ ends|^ hardware/)

{ ORS=" " ; for(i=2;i<=NF;i++) {print $i}}

if(/^}$/) { ORS=" "; print ""}

}'| grep active|awk '{print ,,,,,}'|sed 's/;//g'

注:上述脚本应该在一行,为了方便阅读才分开显示的

输出结果:

192.168.1.195 2005/12/07 01:31:20 2005/12/07 13:31:20 00:0c:29:09:52:d8

192.168.1.194 2005/12/07 01:50:20 2005/12/07 13:50:20 00:e0:4c:c9:86:5

脚本说明:grep -v ^# 过滤掉租约记录里面的注释

awk '{ ....}' 上面已经说明了

里面有个for循环,目的是依次输出从第2个开始到最后的field

grep active 取出处于活动状态的记录,过滤掉过期的记录

awk '{ ...}' 格式化输出

sed 's/;//g' 删除输出中的分号

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航