Go by Example

Line Filters

Build a line filter that transforms stdin and writes results to stdout, with scanner limits and error handling.

A line filter reads text from standard input, where a command receives incoming text, changes each line, and writes results to standard output, where regular results go. A shell pipeline sends one command's output to another command's input.

Scanner reads one line at a time. Write diagnostic messages to standard error, a separate output stream for problems, so they do not mix with the filter results.

package main
 
import (
    "bufio"
    "fmt"
    "os"
    "strings"
)
 
func main() {
    scanner := bufio.NewScanner(os.Stdin)
    for scanner.Scan() {
        fmt.Println(strings.ToUpper(scanner.Text()))
    }
    if err := scanner.Err(); err != nil {
        fmt.Fprintln(os.Stderr, "read error:", err)
        os.Exit(1)
    }
}

In production

Scanner reads one line at a time and has a default maximum line length of about 64 KiB. Increase that limit with Scanner.Buffer before scanning, or use bufio.Reader for longer lines. Return a non-zero exit code on failure so another command can detect the problem. If you buffer output yourself, call Flush to send the saved text before exiting.

Enjoyed this? Get more software craft delivered to your inbox.