I have a list which contains file names(change log) in Jenkins pipeline. I am looking to sort that list based on file extension.
example - lines = [a.yaml, b.sql, c.json, d.py, e.txt]
I would like to sort this list as below- lines = [c.json, d.py, b.sql, e.txt, a.yaml]
Thanks in advance.
CodePudding user response:
You can use Groovy Sort with a custom comparator. Please refer to the following sample.
pipeline {
agent any
stages {
stage('Test') {
steps {
script {
def lines = ["a.yaml", "b.sql", "c.json", "d.py", "e.txt"]
echo "Not sorted: $lines"
sortFiles(lines)
echo "Sorted: $lines"
}
}
}
}
}
@NonCPS
def sortFiles(def files) {
return files.sort { s1, s2 -> s1.substring(s1.lastIndexOf('.') 1) <=> s2.substring(s2.lastIndexOf('.') 1) }
}
Update
Bringing files without a extension to the top
@NonCPS
def sortFiles(def files) {
return files.sort { s1, s2 ->
def s1Index = s1.lastIndexOf('.')
def s2Index = s2.lastIndexOf('.')
if((s1Index == -1)) { // S1 doesn't have an extension, S1 comes first
return -1
} else if (s2Index == -1) { // S1 have an extension but S2 doesn't so s2 comes first
return 1
} else {
return s1.substring(s1Index 1) <=> s2.substring(s2Index 1)
}
}
}