Reading Standard Input (stdin) by Lines in Go

Here’s how to read standard input (stdin) line by line in Go. In can easily be adapted to read from a file as well. This is a pretty common need when creating utilities and command-line filters.

The following is the full code for simple utility that injects line numbers at the beginning of every line.

package main

import (
    "bufio"
    "fmt"
    "log"
    "os"
)

func main() {
    s := bufio.NewScanner(os.Stdin)
    c := 1
    for s.Scan() {
        fmt.Printf("%5v %v\n", c, s.Text())
        c += 1
    }
    if err := s.Err(); err != nil {
        log.Println(err)
    }
}

Remember that this isn’t the best approach if you have data that has exceptionally long lines.

💎 This method of doing it uses os.Scanner one of the greatest advantages of picking Go over other languages for its power to create you own highly performant parsers very quickly. This shows why Go is the first pick — over Python and the rest — for creating command-line utilities, microservices, and other tools. Go is objectively the best at these sorts of things.

#golang #stdin #recipes #utilities #tips