sshark sshark - 8 months ago 52
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:


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


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.



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

    // for each line
    lines.eachWithIndex { line,index ->
        // if line not starts with your comment "'"
            // 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
}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('line.separator')

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