I’m in the process of collecting useful file manipulation scripts I have in Groovy and posting them here. Here are a few for starters:
This script removes lines from a given file that do not match a particular pattern (in this case, the “to_match” regular expression):
File f = new File("file.txt") def lines = [] f.eachLine { if (line =~ /to_match/) lines << line } PrintWriter writer = new PrintWriter(f) lines.each { it -> writer.println(it) } writer.close()
This script replaces the first instance of “to_match” with “replacement” in a file called “input.txt” and saves it:
def f = new File("input.txt") def fileText = f.text fileText = (fileText ~= /to_match/).replaceFirst("replacement") f.write(fileText)
This one downloads a file from a URL, and saves it to disk, using the file name at the end of the URL:
def url = "http://www.techscreen.net/questions/details.txt" def file = new FileOutputStream(url.tokenize("/")[-1]) def outputStream = new BufferedOutputStream(file) outputStream << new URL(url).openStream() outputStream.close()
This script splits an input file into two output files, putting the first 1000 lines into the first file, and the rest in the second:
def lines = [] def lines2 = [] def splitSize = 1000 new File (baseDir, 'input.txt').eachLine { line, nb -> if (nb > splitSize) lines2 << line else lines << line</span> } new File(baseDir, 'output1.txt').withWriter('utf-8') { writer -> lines.each { it -> writer.writeLine(it) } } new File(baseDir, 'output2.txt').withWriter('utf-8') { writer -> lines2.each { it -> writer.writeLine(it) } }