Itai Ganot Itai Ganot - 2 months ago 50
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:

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.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 and in others

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:

itai@Itais-MacBook-Pro ~ - $ groovy populate_jenkins_parameters_cidr_blocks.groovy

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 = ['', '', '', '',''] 
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