简体   繁体   English

Groovy:在文件中获取特定值

[英]Groovy: Get a specific value in a file

I'm quite new in Groovy. 我在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. 我需要获得888888价值。

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.. 但是“ blablabla”的长度可以改变。

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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