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.
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
onDone
callback of thelisten()
method.
To try out our line filter, first make a file with a few lowercase lines.
Then use the line filter to get uppercase lines.
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.