Line Filters in Visual Basic .NET

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 Visual Basic .NET that writes a capitalized version of all input text. You can use this pattern to write your own Visual Basic .NET line filters.

Imports System
Imports System.IO

Module LineFilter
    Sub Main()
        ' Reading from standard input
        Using reader As New StreamReader(Console.OpenStandardInput())
            ' Reading until the end of the stream
            While Not reader.EndOfStream
                ' Read a line of text
                Dim line As String = reader.ReadLine()
                
                ' Convert the line to uppercase
                Dim uppercaseLine As String = line.ToUpper()
                
                ' Write out the uppercased line
                Console.WriteLine(uppercaseLine)
            End While
        End Using
        
        ' Check for errors during reading
        If Console.Error IsNot Nothing Then
            Console.Error.WriteLine("error: " & Console.Error.ToString())
            Environment.Exit(1)
        End If
    End Sub
End Module

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

$ echo 'hello'   > %TEMP%\lines.txt
$ echo 'filter' >> %TEMP%\lines.txt

Then use the line filter to get uppercase lines.

$ type %TEMP%\lines.txt | vbc LineFilter.vb && LineFilter.exe
HELLO
FILTER

In this Visual Basic .NET version:

  1. We use StreamReader to read from the standard input stream (Console.OpenStandardInput()).

  2. We read the input line by line using a While loop and the ReadLine() method, which is similar to the Scan() method in the original example.

  3. We use the ToUpper() method to convert each line to uppercase.

  4. We write the uppercase line to the console using Console.WriteLine().

  5. Error handling is done by checking Console.Error. If there’s an error, we print it to the error stream and exit with a non-zero status code.

  6. The command to compile and run the program is different in Visual Basic .NET. We use vbc to compile and then run the resulting executable.

This example demonstrates how to create a simple line filter in Visual Basic .NET, reading from standard input, processing each line, and writing to standard output.