I am writing a Jenkins pipeline script and need to parse a large log file to find specific error codes. I want to iterate through the file and print only the lines that contain a specific substring, similar to how 'grep' works in Linux. Is there a concise, "Groovy-way" to do this using closures or the eachLine method without writing a complex loop? Also, how should I handle case sensitivity during the search?
3 answers
Groovy makes this incredibly simple with the eachLine method available on File objects. You can use a closure to check each line: new File('path/to/file.log').eachLine { line -> if (line.contains('searchString')) println line }. If you need to handle case-insensitivity, you can convert the line to lowercase using line.toLowerCase().contains('searchstring'). For more advanced filtering, Groovy also supports the findAll method on collections, which allows you to use a regular expression. This is far more efficient than traditional Java BufferedReader loops because Groovy handles the resource management and closing of the file stream automatically behind the scenes, preventing memory leaks in your automation environment.
Does this approach work the same way if I'm trying to filter a list of strings stored in a variable rather than reading directly from a physical file? I'm curious if the performance holds up when dealing with massive arrays of console output in a Groovy-based deployment tool.
The easiest way is using eachLine. It’s short, readable, and handles the file opening/closing for you. It’s perfect for quick Jenkinsfile utility methods.
I agree with Laura. I use this exact snippet in our production pipelines to filter out "WARNING" messages from our build logs. It keeps the console output clean and focuses only on the critical "ERROR" strings we actually need to see.
Steven, if you're working with a list, you can use the grep method which is natively available in Groovy. For example, def matches = myList.grep(~/.*specificString.*/). This uses a Regex pattern and is extremely fast. For very large datasets, using .findAll { it =~ /regex/ } is also highly performant. The beauty of Groovy is that these methods are highly optimized for collection processing, making it a favorite for DevOps engineers who need to filter thousands of lines of log data in seconds.