Skip to content

Instantly share code, notes, and snippets.

@bbrodriges
Created November 15, 2021 13:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bbrodriges/b6ac1cad4866528cced72b8881dbb221 to your computer and use it in GitHub Desktop.
Save bbrodriges/b6ac1cad4866528cced72b8881dbb221 to your computer and use it in GitHub Desktop.
word counter
package main
import (
"bufio"
"flag"
"fmt"
"log"
"os"
)
func main() {
filename := flag.Arg(0)
word := flag.Arg(1)
if filename == "" || word == "" {
log.Fatal("filename and word arguments required")
}
fd, err := os.Open(filename)
if err != nil {
log.Fatalf("cannot open file: %s", err)
}
defer fd.Close()
scanner := bufio.NewScanner(fd)
scanner.Split(bufio.ScanWords)
var wordCount int
for scanner.Scan() {
if scanner.Text() == word {
wordCount++
}
}
if err := scanner.Err(); err != nil {
log.Fatalf("unexpected scanning error: %s", err)
}
fmt.Printf(`Word "%s" found in file %d times\n`, word, wordCount)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment