Read a large file line by line
This program counts the lines of a log file that start with ERROR. It holds one line in memory at a time, so the size of the file does not matter. Save it as count.ant and run it with ant run count.ant app.log:
let args = Os.args()
if args.isEmpty() {
eprintln("usage: ${Path.base(Os.program())} <file>")
Os.exit(2)
}
let input = try File.open(args[0])
defer { input.close() }
var errors = 0
while true {
let line = try input.readLine() ?? break
if line.startsWith("ERROR") {
errors += 1
}
}
println("${errors} errors")2 errors- Get the file name with Os.args. When there is none, write a usage line with eprintln and exit with Os.exit. Os.program gives the script path, and Path.base keeps its last element.
- Open the file with File.open, and close it with File.close in a
deferright after. - Call File.readLine in a loop. Each call returns the next line without its
\nor\r\n, an empty line as"", andnullat the end of the file. - End the loop at
nullwith?? break.tryends the script on a read error, writes the error to standard error and exits with status 1. - Handle the line, here with String.startsWith.
Stop at the first match
Return from inside the loop when the line you want turns up. The rest of the file is never read, and the deferred close runs on every return. String.contains tests each line. The function returns the line number and the line in Result.ok, or Result.ok(null) when no line matches, and the caller turns null into a default with ??:
func firstMatch(path: string, word: string): Result[string | null, Error] {
let input = try File.open(path)
defer { input.close() }
var n = 0
while true {
let line = try input.readLine() ?? break
n += 1
if line.contains(word) {
return Result.ok("${n}: ${line}")
}
}
Result.ok(null)
}
println(try firstMatch("app.log", "timeout") ?? "no match")
println(try firstMatch("app.log", "panic") ?? "no match")4: ERROR timeout
no matchRead a header line first
Read the first line before the loop, then loop over the rest. Every read continues where the last one stopped. Here the loop sums the second column of a CSV file: String.cut splits each line at the first comma, String.toInt parses the number, and ?? continue skips a line without one:
let input = try File.open("sizes.csv")
defer { input.close() }
let header = try input.readLine() ?? ""
println("columns: ${header}")
var total = 0
while true {
let line = try input.readLine() ?? break
let cut = line.cut(",") ?? continue
total += cut.after.toInt() ?? continue
}
println("total: ${total}")columns: name,bytes
total: 25600To parse quoted fields as well, read the whole file with Csv.parse instead.
Write the matching lines to another file
Writes to a file are not buffered: each writeLine goes to the OS. For many small writes, wrap the output in File.buffered. Create the file with File.create and end with an explicit close, which writes out what the buffer holds and reports an error the deferred close cannot:
let input = try File.open("app.log")
defer { input.close() }
let out = File.buffered(try File.create("errors.log"))
defer { out.close() }
while true {
let line = try input.readLine() ?? break
if line.startsWith("ERROR") {
try out.writeLine(line)
}
}
try out.close()
print(try File.read("errors.log"))ERROR disk full
ERROR timeoutRead lines from standard input
To read the lines piped into the script, as in grep -v DEBUG app.log | ant run count.ant, loop over Os.stdin the same way. The program does not open standard input, so it does not close it either:
var errors = 0
while true {
let line = try Os.stdin().readLine() ?? break
if line.startsWith("ERROR") {
errors += 1
}
}
println("${errors} errors")2 errorsRead a small file at once
When the file fits in memory, read it whole with File.read and split it with String.lines, and count the matches with Array.countWhere:
let errors = try File.read("app.log") | String.lines() | Array.countWhere({ x.startsWith("ERROR") })
println("${errors} errors")2 errorsFile.read holds the whole file and String.lines all of its lines, so a file of several gigabytes needs that much memory. The readLine loop does not.
