Groovy:编辑文件

时间:2009-08-25 20:12:13

标签: groovy

我有一个如下所示的示例文件:

CREATE GLOBAL TEMPORARY TABLE tt_temp_user_11
(
asdfa
)
CREATE GLOBAL TEMPORARY TABLE tt_temp_user_11
(
asdfas
)

some other text in file

我想将此文件转换为以下内容:

CREATE GLOBAL TEMPORARY TABLE 1
(
asdfa
)
CREATE GLOBAL TEMPORARY TABLE 2
(
asdfas
)

some other text in file

所以基本上每个TEMPORARY TABLE事件都会附加一个数字。

到目前为止,我有以下groovy脚本:

int i = 0
new File ("C:\\Not_Modified").eachFile{file ->
        println "File name: ${file.name}"
        new File ("C:\\Not_Modified\\"+file.name).eachLine {line ->
                if (line.indexOf("TEMPORARY TABLE")>0)
                {
                    i++
                }
            }
        println "There are ${i} occurences of TEMPORARY TABLE"
    }

如何更改文件中的文字?我应该写一个不同的文件吗?

不过,我的脚本中有目录,因为我将在目录中处理很多这类文件。

我应该选择perl来完成这项任务,但是想尝试一下groovy。

2 个答案:

答案 0 :(得分:2)

我编写了一个类似File.eachLine {}的小功能,但允许编辑。

你可以像这样使用它:

def n=1
modifyFile("filename"){
    if(it.startsWith("CREATE GLOBAL TEMPORARY TABLE"))
        return "CREATE GLOBAL TEMPORARY TABLE " + n++
    return it // Re-inserts unmodified line"
}

这很容易编码 - 从闭包返回的任何内容都写到新文件中。如果您想要一个不同的文件,请提供两个文件名。

    /**
     * This will completely re-write a file, be careful.
     * 
     * Simple Usage:
     *
     * modifyFile("C:\whatever\whatever.txt") {
     *   if(it.contains("soil"))
     *      return null  // remove dirty word
     *   else
     *      return it
     * }
     *
     * The closure must return the line passed in to keep it in the file or alter it, any alteration
     * will be written in it's place.
     *
     * To delete an entire line instead of changing it, return null
     * To add more lines after a given line return: it + "\n" + moreLines
     *
     * Notice that you add "\n" before your additional lines and not after the last
     * one because this method will normally add one for you.
     */
    def modifyFile(srcFile, Closure c) {
        modifyFile(srcFile, srcFile, c)
    }

    def modifyFile(srcFile, destFile, Closure c={println it;return it}) {
        StringBuffer ret=new StringBuffer();
        File src=new File(srcFile)
        File dest=new File(destFile)

        src.withReader{reader->
            reader.eachLine{
                def line=c(it)
                if(line != null) {
                    ret.append(line)
                    ret.append("\n")
                }
            }
        }
        dest.delete()
        dest.write(ret.toString())
    }
}   

答案 1 :(得分:1)

我认为你应该写不同的文件,这是一个很好的做法。 在if {}(而不是i ++)

中加入下面的行
line = line.replaceFirst(/^(create temporary table) (.*)/, "\$1 table${++i}")

然后,在if write line变量之外的outfile

BTW我认为你最好在if而不是indexOf中使用==〜