How to process a file line by line in Go?
Posted on In QAIn 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
}
If you are reading line by line from STDIN:
fs := bufio.NewScanner(os.Stdin)
for fs.Scan() {
txt := fs.Text()
// process txt
}