In my Groovy program, I have a list of lines and want to select a contiguous block of lines from the list. The first line of the desired block contains a particular string, and the last line (which I can include or not - it doesn't matter) contains a (different) marker string.
Working code is below but surely there is a "groovier" way to do this in a line or two - can anyone suggest how?
(Actually my list of lines is from an HTTP GET, but I just define a URL object and do url.openStream().readLines() to get the lines.)
lines = ["line1", "line2", "line3", "line4", "line5", "line6"]
println extract_block("2", "5", lines)
def extract_block(start, end, lines) {
def block = null
for (line in lines) {
if (null == block && line.contains(start)) { block = [] }
if (null != block && line.contains(end)) { break }
if (null != block) { block << line }
}
return block
}
This prints
["line2", "line3", "line4"]
which includes the first line (containing "2") and skips the final line (containing "5").