sshark sshark - 2 months ago 18
Groovy Question

Groovy script to modify text file line by line

I have a input file from which a Groovy file reads input. Once a particular input is processed, Groovy script should be able to comment the input line it used and then move on.

File content:

1
2
3


When it processes line 1 and line 2, the input file will look as below:

'1
'2
3


By this way, if I re-run the Groovy, I would like to start from the line it stopped last time. If a input was used and it failed, that particular line shall not be commented (
'
) so that a retry can be attempted.

Appreciate if you can help to draft a Groovy script.

Thanks

Answer

AFAIK in Groovy you can only append text at the end of the file.

Hence to add ' on each line when it is processed you need to rewrite the entire file.

You can use the follow approach but I only recommend you to use for a small files since you're loading all the lines in memory. In summary an approach for your question could be:

// open the file
def file = new File('/path/to/sample.txt')
// get all lines
def lines = file.readLines()

try{
    // for each line
    lines.eachWithIndex { line,index ->
        // if line not starts with your comment "'"
        if(!line.startsWith("'")){
            // call your process and make your logic...
            // but if it fails you've to throw an exception since
            // you can not use 'break' within a closure
            if(!yourProcess(line)) throw new Exception()

            // line is processed so add the "'"
            // to the current line
            lines.set(index,"'${line}")
        }
     }
}catch(Exception e){
  // you've to catch the exception in order
  // to save the progress in the file
}

// join the lines and rewrite the file
file.text = lines.join(System.properties.'line.separator')

// define your process...
def yourProcess(line){
    // I make a simple condition only to test...
    return line.size() != 3
}