Go · lesson 22 of 30 · Files and errorsCount words from standard input
A Scanner can split by words. The program reads a file after < or the output of another command.
22-word-count.go Download 22-word-count.go
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
// a scanner splits its input by lines, or by words if you ask for it
in := bufio.NewScanner(os.Stdin)
in.Split(bufio.ScanWords)
count := map[string]int{}
total := 0
for in.Scan() {
count[in.Text()]++
total++
}
if err := in.Err(); err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println(total, "words,", len(count), "different")
fmt.Println("the word files:", count["files"])
}
Terminal
$ ./22-word-count < words.txt
18 words, 16 different
the word files: 1
$ echo "copy the files" | ./22-word-count
3 words, 3 different
the word files: 1Exercise
Remove full stops and commas before you count.
TurboShell does not contain Go. These programs are made in Bucket & Code with its Go runtime; the finished file runs on the NAS without Go.