Line Filters in Dart
A line filter is a common type of program that reads input on stdin, processes it, and then prints some derived result to stdout. grep and sed are common line filters.
Here’s an example line filter in Dart that writes a capitalized version of all input text. You can use this pattern to write your own Dart line filters.
import 'dart:io';
import 'dart:convert';
void main() {
// Wrap stdin with a StreamReader for convenient line-by-line reading
var reader = stdin.transform(utf8.decoder).transform(LineSplitter());
// Read input line by line
reader.listen((String line) {
// Convert the line to uppercase
var ucl = line.toUpperCase();
// Write out the uppercased line
print(ucl);
}, onDone: () {
// Check for errors during reading
if (stdin.hasError) {
stderr.writeln('error: ${stdin.error}');
exit(1);
}
});
}In this Dart version:
We use
stdin.transform()to create a stream of UTF-8 decoded lines from the standard input.The
listen()method is used to process each line as it’s read. This is similar to theScan()method in the original example.We use
line.toUpperCase()to convert each line to uppercase.The
print()function is used to output each processed line.Error handling is done in the
onDonecallback of thelisten()method.
To try out our line filter, first make a file with a few lowercase lines.
$ echo 'hello' > /tmp/lines
$ echo 'filter' >> /tmp/linesThen use the line filter to get uppercase lines.
$ cat /tmp/lines | dart run line_filters.dart
HELLO
FILTERNote that in Dart, we use dart run to execute our script. Make sure to save the code in a file named line_filters.dart before running the command.