Skip to content

Instantly share code, notes, and snippets.

@Adron
Created January 29, 2019 22:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Adron/3c22e6880e347b95863f980b88af3b96 to your computer and use it in GitHub Desktop.
Save Adron/3c22e6880e347b95863f980b88af3b96 to your computer and use it in GitHub Desktop.
Duplicate line finder in Go
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
counts := make(map[string]int)
files := os.Args[1:]
if len(files) == 0 {
countLines(os.Stdin, counts)
} else {
for _, arg := range files {
f, err := os.Open(arg)
if err != nil {
fmt.Printf("The Error Happened! %s", os.Stderr)
continue
}
countLines(f, counts)
errFile := f.Close()
if errFile != nil {
fmt.Println("Holy moley the file didn't close correctly!")
}
}
}
for line, n := range counts {
if n > 1 {
fmt.Printf("%d\t%s\n", n, line)
}
}
}
func countLines(f *os.File, counts map[string]int) {
input := bufio.NewScanner(f)
for input.Scan() {
counts[input.Text()]++
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment