How can I read a snippet from a file using groovy?

I am reading a file into groovy using this simple example code

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

      

For example my file has 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 row with rowid that also has a semicolon at the end. then I want to read back to '(select'

So after reading this file, I want to have a line containing:

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

      

Is it possible? And How?

+2


source to share


2 answers


If the content of your file is small, it is easy enough to read the whole file and then use a little regex to get the elements 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 }

      



Outputs:

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

      

+1


source


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



The result you are looking for is subscriptions from list.lastIndexOf('(select')

to the end of the list.

0


source







All Articles