Created
January 29, 2019 22:08
-
-
Save Adron/3c22e6880e347b95863f980b88af3b96 to your computer and use it in GitHub Desktop.
Duplicate line finder in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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