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 from standard input, transforms each line, and writes results to standard output. This lets command-line tools compose in shell pipelines.

Scanner reads one line at a time. Write diagnostics to stderr so they do not mix with the filter output.

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's default token buffer is 64 KiB, including any line delimiter; raise it with Scanner.Buffer before the first scan or use bufio.Reader for longer lines. Return a non-zero exit code on failure so shell scripts can detect errors. If you buffer stdout yourself, flush it before exit.

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