views:

590

answers:

2

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?

+1  A: 

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;
Bart Kiers
thanks! that regex seems interesting but it is not working for me. in your test.txt file do you have the data in seperate lines or all in one line?
Drake
@Drake: they're all on separate lines. When the input is a string without line breaks, it still works (output: '(Select * from some table where something = something) on rowid = something;').For the records: I'm using Groovy 1.6
Bart Kiers
... but if no line breaks are present in the input file, I would change my regex slightly: no greedy DOT-STARS in that case!
Bart Kiers
A: 

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.

Aaron Digulla
list doesnt have 'lastIndexOf' method
Drake
It does in Groovy.
Aaron Digulla
http://groovy.codehaus.org/groovy-jdk/java/util/List.html I couldnt find it in the API. do you have a link where its shown in an example?
Drake
Odd. It's mentioned in the docs (http://groovy.codehaus.org/JN1015-Collections) and as fixed in GROOVY-1007 (http://jira.codehaus.org/browse/GROOVY-1007)
Aaron Digulla