4

I am trying to read a text file and return all lines that do not begin with a #. In python I could easily use list comprehension list

with open('file.txt') as f:
     lines = [l.strip('\n') for l in f.readlines() if not re.search(r"^#", l)]

I would like to accomplish the same thing via Groovy. So far I have the below code, any help is greatly appreciated.

lines = new File("file.txt").readLines().findAll({x -> x ==~ /^#/ })
Chris Powell
  • 175
  • 3
  • 7

1 Answers1

5

In groovy, you generally have to use collect in place of list comprehensions. For example:

new File("file.txt").readLines().findAll({x -> x ==~ /^#/ }).
    collect { it.replaceAll('\n', '') }

Note that readLines() already strips off newlines, so in this case it's not necessary.

For searching, you can also use the grep() method:

new File('file.txt').readLines().grep(~/^#.*/)
ataylor
  • 64,891
  • 24
  • 161
  • 189