Skip to content

Instantly share code, notes, and snippets.

@Adron
Created Jan 29, 2019
Embed
What would you like to do?
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