Fullmenu null

 

23 August 2017

In some operating systems we have the command grep or find that look for a string in the files in a directory and dump it by console. With this script we are going to do something similar to see how we can read large files and how to write it to another file.

if( args.length != 3){
    println "Hey necesito el fichero de entrada, el de salida y la cadena a buscar"
    return
}

inputFile = new File(args[0])
outputFile = new File(args[1])
search = args[2]

outputFile.newWriter().withWriter { writer-> // (1)
    inputFile.eachLine { line, indx -> // (2)
        if (line.indexOf(search) != -1)
            writer << "$indx: $line\n" // (3)
    }
}
  1. We create or overwrite an output file and use a writer to write it

  2. readLine is indicated for reading large files, having other ways of reading a file such as .text that would read all file in a string

  3. We use the operator leftshit to send strings to the file


Script
if( args.length != 3){
    println "Hey necesito el fichero de entrada, el de salida y la cadena a buscar"
    return
}

inputFile = new File(args[0])
outputFile = new File(args[1])
search = args[2]

outputFile.newWriter().withWriter { writer-> // (1)
    inputFile.eachLine { line, indx -> // (2)
        if (line.indexOf(search) != -1)
            writer << "$indx: $line\n" // (3)
    }
}