awk函数实现将点分式形式的掩码转换为十进制形式的掩码
在用awk处理文本时,需要将源数据为点分式形式的掩码转换为十进制形式的掩码,下边的函数可简单实现:
- 转换功能函数cdr2mask
function cdr2mask(mask_point) {
num=gsub("255.","",mask_point)
#print mask_point
gsub("[\\.]0","",mask_point)
#print mask_point
mask=mask_point-0
for(i = 0;mask > 0;i++){
if (mask % 2^(7-i) == 0){
i++
break
}else{
mask -= 2^(7-i)
}
}
mask_decade = 8*num + i
return mask_decade
}
- 源数据
<ZJHZ-BA-IPNET-RT07-NE40EX16A>dis cur configuration bgp
#
ipv4-family vpn-instance ChinaMobile_IMS_Media
network 10.3.160.20 0.0.0.0
network 10.3.160.48 255.255.255.252
network 10.3.160.56 255.255.255.128
- awk完整程序
#!/bin/awk -f
# author: wholj
# date: 2018-09-05
# awk开始处理文本
# JSON构造函数
function json(dict,end_tag)
{
count=0
printf("\t{\n")
for(key in dict){
++count
if(count==length(dict)){
printf("\t\t\"%s\":\"%s\"\n",key,dict[key])
}
else{
printf("\t\t\"%s\":\"%s\",\n",key,dict[key])
}
}
if(end_tag==1){
printf("\t}\n")
}
else{
printf("\t},\n")
}
}
# 将点分式形式的掩码转换为十进制形式的掩码(255.255.255.0 --> 24)
function cdr2mask(mask_point) {
num=gsub("255.","",mask_point)
#print mask_point
gsub("[\\.]0","",mask_point)
#print mask_point
mask=mask_point-0
for(i = 0;mask > 0;i++){
if (mask % 2^(7-i) == 0){
i++
break
}else{
mask -= 2^(7-i)
}
}
mask_decade = 8*num + i
return mask_decade
}
# awk开始处理传入的文本文件
{
# 将文件中的\r换行替换为\n
gsub("\r","\n",$0)
# 获取VPN的名称
if ( NF==3 && $1~/ipv4-family/ && $2~/vpn-instance/ ){
#print $0
vpn_name = $3
#print vpn_name
}
# 得到路由信息
if( NF==3 && $1~/network/ && $2~/[0-9]+.[0-9]+.[0-9]+.[0-9]+/ && $3~/[0-9]+.[0-9]+.[0-9]+.[0-9]+/ ){
#print $0
#print cdr2mask($3)
route_info[vpn_name, NR] = vpn_name"|"$2"/"cdr2mask($3)
#print route_info[vpn_name, NR]
}
}
END{
print "["
row_count=0
# 遍历数组,组合json格式
for( route in route_info ){
++row_count
split(route_info[route], route_arr, "|")
#print route_arr[1]
#print route_arr[2]
route_dict["vpn_name"]=route_arr[1]
route_dict["route_info"]=route_arr[2]
if ( row_count==length(route_info) ){
json(route_dict,"1")
}else{
json(route_dict,"0")
}
}
print "]"
}
- 测试结果
[
{
"vpn_name":"ChinaMobile_IMS_Media",
"route_info":"10.3.160.20/0"
},
{
"vpn_name":"ChinaMobile_IMS_Media",
"route_info":"10.3.160.48/30"
},
{
"vpn_name":"ChinaMobile_IMS_Media",
"route_info":"10.3.160.56/25"
}
]
by: wholj
email: wholj7650@163.com