josh
josh

Reputation: 231

How to read a snippet from a file using groovy?

I am reading a file in groovy using this simple sample code

file.eachLine {line->
 // do something with line
}

For example my file has some data like this

blah blah blah 
This is some more lines
more lines
Insert into something
(x1,x2,x3)
(Select * from
some table
where 
something = something)
on rowid = something;

So I want to read a snippet. If I see a line with rowid that also has a 'semicolon' at the end. then I want to read back till '(select'

So after reading this file I want to have a string that contains:

(Select * from
    some table
    where 
    something = something)
    on rowid = something;

Is that possible? and how?

Upvotes: 2

Views: 8291

Answers (2)

Aaron Digulla
Aaron Digulla

Reputation: 328624

Collect the lines in a list and when you notice the ";", stop the implicit loop by throwing an exception.

The result you seek is the sublist from list.lastIndexOf('(select') to the end of the list.

Upvotes: 0

Bart Kiers
Bart Kiers

Reputation: 170178

If the contents of your file is small, it's easy enough to read the file in it's entire and then use a bit of regex to get the part(s) you want:

def file = new File('/home/bart/Temp/test.txt')
def contents = file.getText()
def matcher = contents =~ /\(Select[^)]++\)\s++.*?rowid\s=\s.*;/
matcher.each { println it }

Produces:

(Select * from
some table
where 
something = something)
on rowid = something;

Upvotes: 1

Related Questions