Itai Ganot Itai Ganot - 11 months ago 158
Groovy Question

How to sort the output to exclude a regex pattern?

I have the following Groovy code which queries AWS to receive a list of CIDR blocks in use and populate an array with it:

#!/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
}


In some regions the CIDR blocks are 172.31.0.0/16 and in others 10.100.0.0/16.

I want the output of the script to include only 10.100.* CIDR blocks and I don't want the 172.* networks to even appear in the output.

Current output looks like so:

[email protected] ~ - $ 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


How can it be done?

Rao Rao
Answer Source

On the output collection, you can apply filter using find or findAll as shown below.

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()

You can quickly try it online demo

EDIT: Based on the comment. Remove last 8 statements in your code and just add just below statements.

output.findAll{ it =~ /10.100.*/ }.sort()
println output
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download