Sort filenames from the output of "findFiles glob:" in Jenkins pipeline

Viewed 223
  steps {
    node('master') {
      script {
        def files = findFiles glob: "*/test/*.*"
        files.sort()
        echo "${files[i].name}"
      }
    }
  }

I have files inside test directory where filenames having a pattern test1.csv, test2.csv ... test100.csv, test101.csv etc.

When I use files.sort(), Jenkins prints test100.csv, test101.csv first and then test1.csv.

How to sort and print like test1, test2, test3 ... test100 etc.

Please advice.

1 Answers

Instead of using groovy, I suggest you to do it with sh. Abusing groovy for simple tasks like this one is considered a bad practice, unless you need that list in other steps/operations. Eventually you just want to print it on stdout, so:

ls *.csv | sort -n -k 1.5

With sort you can specify the -n, --numeric-sort to compare according to the numerical value and a key definition -k, --key to sort using a key. That 1.5 means: take the first field (the whole word unless you specify a separator with -t) and starts comparing from the 5th character, which is the first digit after test.

Related