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:

  1. We use Needs["GeneralUtilities"]` to import utility functions.

  2. The lineFilter function is defined as a module that reads input line by line using Input[].

  3. We use a While loop to continuously read input until EndOfFile is encountered.

  4. The ToUpperCase function is used to convert each line to uppercase.

  5. We use Print to output the uppercase line.

  6. Error checking is done by examining $MessageList for any error messages.

  7. The script can be saved as linefilter.wl and executed using wolframscript.

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.