Skip to content

Instantly share code, notes, and snippets.

@allenaven
Created July 7, 2017 02:59
Show Gist options
  • Save allenaven/9bc8e1144396e506687b32487a042b3c to your computer and use it in GitHub Desktop.
Save allenaven/9bc8e1144396e506687b32487a042b3c to your computer and use it in GitHub Desktop.
Golang snippet to detect file duplicates in a directory by comparing MD5 checksums.
// Tool to check for duplicates in a directory by calculating and comparing
// md5 checksums on the directory contents
package main
import (
"crypto/md5"
"encoding/hex"
"fmt"
"io/ioutil"
"os"
)
func main() {
files, _ := ioutil.ReadDir(os.Args[1])
s, sep := "", ""
for _, f := range files {
fullname := os.Args[1] + "/" + f.Name()
md5sum := checksum(fullname)
s += sep + f.Name() + "\n" + "MD5 checksum: " + md5sum + "\n"
sep = "\n"
}
fmt.Printf(s + sep)
}
func checksum(fname string) string {
data, err := ioutil.ReadFile(fname)
if err != nil {
fmt.Printf("Error on " + fname)
}
sum := md5.Sum(data)
return hex.EncodeToString(sum[:])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment