How to process a file line by line in Go?

In the Go programming language, How to process a file line by line?

An equivalent piece of Bash code could be

while read line ; do
    echo $line
done < ./input.txt

You can make use of the bufio package’s Scan().

// open the file filepath
f := os.Open(filepath)
// create a scanner
fs := bufio.NewScanner(f)

// scan file https://golang.org/pkg/bufio/#Scanner.Scan
for fs.Scan() {
        txt := fs.Text()
        // do anything with txt
}
Answered by Eric Z Ma.

If you are reading line by line from STDIN:

fs := bufio.NewScanner(os.Stdin)
for fs.Scan() {
    txt := fs.Text()
    // process txt
}

Eric Z Ma

Eric is a father and systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

Your email address will not be published. Required fields are marked *