如何对输出进行排序以排除正则表达式模式?

问题描述 投票:0回答:2

我有以下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
2个回答
1
投票

在输出集合上,您可以使用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

1
投票

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

你可以在收集它们之前尽早完成。所以改变:

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

p.text.eachLine { line ->
  if (!(line =~ /^172\./)) output << line
}
© www.soinside.com 2019 - 2024. All rights reserved.