【问题标题】:Config parsing with awk使用 awk 进行配置解析
【发布时间】:2017-01-18 13:34:39
【问题描述】:

我正在尝试学习一些 awk 魔法,并尝试根据以下规则解析数据:

如果 allow-service 部分包含 default、https:any、all、ssh:any、ssh:tcp 我希望在每个不兼容的接口的一行上输出接口名称和匹配的服务。

我的数据看起来像这样:

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

附加条件:

  • 必须是oneliner
  • 我不能使用 bash 脚本,但我可以使用 bash 命令
  • 它必须以 awk 脚本结尾

非常特殊的限制,我知道。

我开始四处寻找,发现它只给了我允许服务部分中的数据,但它会显示尾随“}”,我还没有弄清楚如何保存接口名称:

awk 'BEGIN {RS="net self [A-Za-z0-9_]+ {\n[ ]+";ORS="=";}{print;}'

非常感谢任何帮助或推动正确方向!

/帕特里克

【问题讨论】:

  • default10 重复两次。请编辑输出
  • 谢谢老兄,非常感谢

标签: linux bash parsing awk curly-braces


【解决方案1】:

使用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

【讨论】:

  • 永远不要使用printf $<anything>,因为如果/当$<anything> 包含 printf 格式字符时它会失败。总是做printf "%s", $<anything>。 @PatrikJ 你问了一个问题并接受了你在提出问题后一小时内得到的第一个答案。我并不是说这不是所有方面的最佳答案,但我们永远不会知道,因为其他人都在跳过你的问题,因为你已经接受了答案。
猜你喜欢
  • 2013-03-03
  • 2020-01-25
  • 2020-09-13
  • 2011-04-07
  • 2012-04-20
  • 1970-01-01
  • 2013-02-12
  • 2017-07-10
  • 2012-12-24
相关资源
最近更新 更多