如何解决awk解析文本文件问题
我刚刚开始学习如何使用awk解析和打印文本文件。
我从下面的波纹管代码开始,谁可以帮助我?
NB:输出文件中必须使用引号(请参见所需的输出)
awk '/^IPDATA=/ && /A|B|C| '{print "ADD IP ="$0"\n(\n \Ref "$1",Type vlan="$2"\"\n)\n"}' file > file1
注意:Ref是IPREF行的总和,在此示例中,我们有三个:[2] && [2] && [1]。
示例文本文件实际上很大,但是我已经总结了一下:
IPDATA=A IPID A
IPDATA=A IPREF [2] =
--- IPREF = VRID=A_1
--- IPREF = VRID=A_2
IPDATA=B IPID B
IPDATA=B IPREF [2] =
--- IPREF = VRID=B_1
--- IPREF = VRID=B_2
IPDATA=C IPID C
IPDATA=C IPREF [1] =
--- IPREF = VRID=C_1
我想得到以下结果:
"ADD IP=A "
( Ref 2
"Type vlan=VRID=A_1"
"Type vlan=VRID=A_2"
)
"ADD IP=B "
( Ref 2
"Type vlan=VRID=B_1"
"Type vlan=VRID=B_2"
)
"ADD IP=C "
( Ref 1
"Type vlan=VRID=C_1"
)
谢谢
解决方法
您能否仅在GNU awk
中尝试使用所示示例进行跟踪,编写和测试。
awk -v s1="\"" '
/^IPDATA/ && /IPID .*/{
if(FNR>1){ print ")" }
print s1 "ADD IP" s1 "="s1 $NF OFS s1
next
}
/^IPDATA.*IPREF.*\[[0-9]+\]/{
match($0,/\[[^]]*/)
print "( Ref sum of IPREF " substr($0,RSTART+1,RLENGTH-1)
next
}
/^--- IPREF/{
print s1 "Type vlan="$NF s1
}
END{
print ")"
}
' Input_file
说明: 添加以上详细说明。
awk -v s1="\"" ' ##Starting awk program from here.
/^IPDATA/ && /IPID .*/{ ##Checking condition if line starts IPDATA and having IPID here.
if(FNR>1){ print ")" } ##Checking condition if FNR>1 then printing ) here.
print s1 "ADD IP" s1 "="s1 $NF OFS s1 ##Printing s1 ADD IP s1 equal to s1 last field OFS and s1 here.
next ##next will skip all further statements from here.
}
/^IPDATA.*IPREF.*\[[0-9]+\]/{ ##Checking condition if line starts from IPDATA and having IPREF till [ digits ].
match($0,/\[[^]]*/) ##Using match to match from [ till ] in line.
print "( Ref sum of IPREF " substr($0,RLENGTH-1) ##printing string as per request and sub-string from RSTART+1 to till RLENGTH-1 here.
next
}
/^--- IPREF/{ ##Checking conditon if line starts from --- IPREF then do following.
print s1 "Type vlan="$NF s1 ##Printing s1 string last field and s1 here.
}
END{ ##Starting END block of this program from here.
print ")" ##Printing ) here.
}
' Input_file ##Mentioning Input_file name here.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。