Line Filters in Julia

Our line filter program reads input from stdin, processes it, and then prints a derived result to stdout. In this case, it writes a capitalized version of all input text. You can use this pattern to write your own Julia line filters.

using Printf

# Wrapping the unbuffered stdin with a buffered reader gives us a convenient
# readline method that advances the reader to the next line.
reader = stdin

# Read lines from stdin until EOF
for line in eachline(reader)
    # Convert the line to uppercase
    ucl = uppercase(line)
    
    # Write out the uppercased line
    println(ucl)
end

# Check for errors during reading
if !eof(reader)
    @error "Error reading input: $(error())"
    exit(1)
end

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 | julia line-filters.jl
HELLO
FILTER

In this Julia version:

  1. We use the built-in stdin for input, which is already buffered in Julia.
  2. The eachline function provides an iterator over the lines of input.
  3. We use uppercase to convert each line to uppercase.
  4. println is used to write the uppercased line to stdout.
  5. Error checking is done by testing if we’ve reached the end of the file (EOF) after the loop.

Julia’s standard library provides high-level constructs that make this kind of text processing straightforward and efficient.