简体   繁体   中英

Groovy: Get a specific value in a file

I'm quite new in Groovy. Basically I load a text file, then I need to get a specific value at one line (actually the 6th).

The line is like:
STATIC_ASSERT(VERSION == 888888, "blablabla");

I need to get the 888888 value.

I found a way using multiple split but it's ugly.

I also think of using something like:
line.substring(ind+"VERSION ==".length(), line.length()-10).trim();

But the "blablabla" length can change..

Thank you.


Edit: It works using an hardcoded string like this.

But when I try to run it from the file I get this error:

test' is failed: org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: 
script1516208488151762512206.groovy: 4: expecting '}', found '' @ line 4, column 69. 
ne.contains('VERSION ==') 
^ 

1 error 

Here is my code:

${groovy:
    String Ver
    def file = new File("C:\\test.cpp")
    def data = file.filterLine { line -> 
        line.contains('VERSION ==')
    }
    Ver = data.split("==")[1].split(",")[0].trim()

    logger.info(Ver)
}

-- I also tried something like this:

${groovy:
    String Ver
    def file = new File("C:\\test.cpp")
        while ((line = file.readLine())!=null) 
        {
           int ind = line.indexOf("VERSION ==")
           if (ind >= 0)
           {
               Ver = line.split("==")[1].split(",")[0].trim()
           }
        }
        logger.info(Ver)
    }

But I get same kind of weird error:

expecting '}', found '' @ line 9, column 58. 
("==")[1].split(",")[0].trim() 
^ 

1 error 

:(

You do as shown below:

def line = 'STATIC_ASSERT(VERSION == 888888, "blablabla");'
println line.split('==')[1].split(',')[0].trim()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM