Line Filters in Wolfram Language
(* 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 Wolfram Language that writes a
capitalized version of all input text. You can use this
pattern to write your own Wolfram Language line filters. *)
(* Import the required functions *)
Needs["GeneralUtilities`"]
(* Define the main function *)
lineFilter[] := Module[{},
(* Read input line by line *)
While[True,
line = Input[];
If[line === EndOfFile, Break[]];
(* Convert the line to uppercase *)
ucl = ToUpperCase[line];
(* Write out the uppercased line *)
Print[ucl];
];
(* Check for errors during input *)
If[!FreeQ[$MessageList, _],
PrintTemporary["Error occurred during input processing"];
Exit[1];
];
]
(* Run the line filter *)
lineFilter[]
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 | wolframscript -code "<<linefilter.wl"
HELLO
FILTER
In this Wolfram Language version:
We use
Needs["GeneralUtilities
"]` to import utility functions.The
lineFilter
function is defined as a module that reads input line by line usingInput[]
.We use a
While
loop to continuously read input untilEndOfFile
is encountered.The
ToUpperCase
function is used to convert each line to uppercase.We use
Print
to output the uppercase line.Error checking is done by examining
$MessageList
for any error messages.The script can be saved as
linefilter.wl
and executed usingwolframscript
.
Note that Wolfram Language doesn’t have a direct equivalent to Go’s bufio.Scanner
, so we use a simpler approach with Input[]
. Also, error handling is different in Wolfram Language, so we check $MessageList
for any errors that occurred during execution.