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/linesThen use the line filter to get uppercase lines.
$ cat /tmp/lines | wolframscript -code "<<linefilter.wl"
HELLO
FILTERIn this Wolfram Language version:
We use
Needs["GeneralUtilities"]` to import utility functions.The
lineFilterfunction is defined as a module that reads input line by line usingInput[].We use a
Whileloop to continuously read input untilEndOfFileis encountered.The
ToUpperCasefunction is used to convert each line to uppercase.We use
Printto output the uppercase line.Error checking is done by examining
$MessageListfor any error messages.The script can be saved as
linefilter.wland 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.