我正在尝试学习一些 awk 魔法,并且正在尝试根据这些规则解析数据:
如果 allow-service 部分包含 default、https:any、all、ssh:any、ssh:tcp,我希望为每个不兼容的接口(interface)在一行中输出接口(interface)名称和匹配的服务。
我的数据看起来像这样:
net self interface1 {
allow-service none
}
net self interface2 {
allow-service none
}
net self interface3 {
allow-service {
icmp:any
}
}
net self interface4 {
allow-service {
icmp:any
}
}
net self interface5 {
allow-service {
icmp:any
default
}
}
net self interface6 {
allow-service all
}
net self interface7 {
allow-service {
icmp:any
8888:tcp
9999:any
}
}
net self interface8 {
allow-service {
icmp:any
default
}
}
net self interface9 {
allow-service {
https:any
ssh:any
icmp:any
}
}
net self interface10 {
allow-service {
icmp:any
default
}
}
我希望得到的输出是这样的:
interface5, default
interface6, all
interface8, default
interface9, https:any, ssh:any
interface10, default
附加条件:
- 必须是单行本
- 我不会使用 bash 脚本,但我可以使用 bash 命令
- 它必须以 awk 脚本结尾
我知道非常特殊的限制。
我开始四处寻找,发现这只给我允许服务部分中的数据,但它会显示尾随“}”,我还没有想出如何保存接口(interface)名称:
awk 'BEGIN {RS="net self [A-Za-z0-9_]+ {\n[ ]+";ORS="=";}{print;}'
非常感谢任何帮助或插入正确的方向!
/帕特里克
最佳答案
使用 gawk
awk -F" " -v RS="{|}|allow-service|\n" '/(https|ssh):any|all|default/{printf "%s, %s",prev,$1;prev="";u=2} /net self/{prev=$3} /net self/&&u==2{u=0;printf "\n"}' file
输出
interface5, default
interface6, all
interface8, default
interface9, https:any, ssh:any
interface10, default
分解
-F" "
RS="{|}|allow-service|\n"
'/(https|ssh):any|all|default/{printf "%s, %s",prev,$1;prev="";u=2} # print the values and set u-used to 2
/net self/{prev=$3} #store interface
/net self/&&u==2{u=0;printf "\n"} #print tags in new-line
关于linux - 使用awk解析配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39427857/