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:

  1. We use stdin.transform() to create a stream of UTF-8 decoded lines from the standard input.

  2. The listen() method is used to process each line as it’s read. This is similar to the Scan() method in the original example.

  3. We use line.toUpperCase() to convert each line to uppercase.

  4. The print() function is used to output each processed line.

  5. Error handling is done in the onDone callback of the listen() method.

To try out our line filter, first make a file with a few lowercase lines.

$ echo 'hello'   > /tmp/lines
$ echo 'filter' >> /tmp/lines

Then use the line filter to get uppercase lines.

$ cat /tmp/lines | dart run line_filters.dart
HELLO
FILTER

Note 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.