【问题标题】:How to sort the output to exclude a regex pattern?如何对输出进行排序以排除正则表达式模式?
【发布时间】:2018-06-03 22:54:56
【问题描述】:

我有以下 Groovy 代码,它查询 AWS 以接收正在使用的 CIDR 块列表并用它填充数组:

#!/usr/local/bin/groovy
def regions = ['us-west-2', 'us-east-1', 'eu-west-1']
        def output = []
        regions.each { region ->
            def p = ['/usr/bin/aws', 'ec2', 'describe-vpcs', '--region', region].execute() | 'grep -w CidrBlock'.execute() | ['awk', '{print $2}'].execute() | ['tr', '-d', '"\\"\\|,\\|\\{\\|\\\\["'].execute() | 'uniq'.execute()
            p.waitFor()
            p.text.eachLine { line ->
                output << line
            }
        }
        output = output.sort { a, b ->
        def aparts = a.split('[./]').collect { it as short }
        def bparts = b.split('[./]').collect { it as short }
        (0..4).collect { aparts[it] <=> bparts[it] }.find() ?: 0
        }
        output.each {
            println it
        }

在某些地区,CIDR 块为 172.31.0.0/16,而在其他地区为 10.100.0.0/16。

我希望脚本的输出仅包含 10.100.* CIDR 块,并且我不希望 172.* 网络出现在输出中。

当前输出如下所示:

itai@Itais-MacBook-Pro ~ -  $ groovy populate_jenkins_parameters_cidr_blocks.groovy
172.30.0.0/16
172.31.0.0/16
10.100.0.0/16
10.105.0.0/16

怎么做?

【问题讨论】:

    标签: regex amazon-web-services sorting groovy filtering


    【解决方案1】:

    最好的解决方案是尽早消除不需要的块。

    你可以在收集它们的时候就这样做。所以改变:

    p.text.eachLine { line ->
      output << line
    }
    

    p.text.eachLine { line ->
      if (!(line =~ /^172\./)) output << line
    }
    

    【讨论】:

      【解决方案2】:

      在输出集合上,您可以使用findfindAll 应用过滤器,如下所示。

      def outputCollection = ['172.30.0.0/16', '172.31.0.0/16', '10.100.0.0/16', '10.100.0.1/16','10.105.0.0/16'] 
      println outputCollection.findAll{ it =~ /10.100.*/ }.sort()
      

      大家可以在线快速试用demo

      编辑:根据评论。 删除代码中的最后 8 条语句,然后在下面添加语句。

      output.findAll{ it =~ /10.100.*/ }.sort()
      println output
      

      【讨论】:

      • 当您在脚本中执行println output 时会显示什么?希望您根据上面的示例得到了必须做的事情?即,查找并申请regex
      • @ItaiGanot,我可以建议你先看看演示,看看它是否能产生你想要的输出吗?
      • 我已将输出行编辑为: output = output.findAll{ it =~ /10.100.*/ }.sort ,现在看来它可以正常工作,但它不是一个好指示目前只有一个 CIDR 启动,当另一个启动时我会尽快更新,谢谢
      • 您说it works ok, but it is not good indication 会让人感到困惑。对有用的答案表示赞赏,如果解决了问题,请接受它作为已回答的答案。
      • @ItaiGanot,但可以在演示示例中看到差异,因为它的集合中有其他 IP。并进行过滤。
      猜你喜欢
      • 1970-01-01
      • 2020-08-18
      • 1970-01-01
      • 1970-01-01
      • 2011-03-01
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      相关资源
      最近更新 更多