Groovy: editing a file

I have an example file, for example:

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

some other text in file

I want to convert this file to the following:

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

some other text in file

Thus, in each case, a number will be added to each TEMPORARY TABLE record.

So far I have the following groovy script:

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"
    }

How can I change the text in a file? Should I write to another file?

btw, I have a directory in my script, because I will work on a large number of these types of files in the directory.

I should have chosen perl for this task, but wanted to give groovy a try.

0
source share
2 answers

I think you should write to another file, this is a good practice. Put something like the line below inside your if {} (instead of i ++)

line = line.replaceFirst(/^(create temporary table) (.*)/, "\$1 table${++i}")

if outfile

, , == ~ if indexOf

+1

, 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 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())
    }
}   
+2

All Articles