unix - awk 解析文本文件问题
问题描述
我刚刚开始学习如何使用 awk 来解析和打印文本文件。
我从下面的代码开始,谁能帮助我?
注意:在输出文件中引用是强制性的(请参阅所需的输出)
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,RSTART+1,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.
推荐阅读
- ruby-on-rails - 头像图像未从 React 客户端传递到 Rails API
- php - 如何在移动设备的重定向页面上传递 PHP 会话值?
- rxjs - API 返回一个我需要解析的数组;每个项目一个请求
- c++ - iter++->empty() 和 ++iter->empty() 有什么区别?
- location - 我有一个只有 x,y 坐标和 x' 和 y 值的数据集通过另一种算法传给我
- php - Wordpress - 如何使用 URL 中的搜索查询参数“标签”注册自定义分类并使其工作?
- node.js - 不确定为什么在使用 express-session 时没有 cookie 被发送回我的 localhost 客户端
- node.js - 在 Node.js 应用程序中格式化 JSON 内容的最佳方式
- javascript - JS 添加活动悬停项目列表
- php - PDO Prepared Statement 未按预期在 MySQL 中创建表