簡體   English   中英

如何對輸出進行排序以排除正則表達式模式?

[英]How to sort the output to exclude a regex pattern?

我有以下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

如何做呢?

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

您可以快速在線試用

編輯:基於評論。 刪除代碼中的最后8條語句,然后僅添加以下語句。

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

最好的解決方案是盡早消除不需要的塊。

您可以盡早收集它們。 所以改變:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM