Created
May 12, 2016 11:51
-
-
Save nytr0gen/94fa32463abda8ea722c4e950ee2e36c to your computer and use it in GitHub Desktop.
sort unique all files in golang
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
import ( | |
"errors" | |
"io/ioutil" | |
"os" | |
"os/exec" | |
) | |
func UniqueFiles(files ...string) (err error) { | |
if len(files) == 0 { | |
return errors.New("no files provided") | |
} | |
for _, name := range files { | |
if err = createIfNotExists(name); err != nil { | |
return | |
} | |
} | |
var args = []string{"-u"} | |
args = append(args, files...) | |
cmd := exec.Command("sort", args...) | |
// open the out file for writing | |
outfile, err := ioutil.TempFile("", "") | |
if err != nil { | |
return | |
} | |
defer outfile.Close() | |
cmd.Stdout = outfile | |
if err = cmd.Start(); err != nil { | |
return | |
} | |
cmd.Wait() | |
return os.Rename(outfile.Name(), files[0]) | |
} | |
func createIfNotExists(name string) error { | |
f, err := os.OpenFile(name, os.O_CREATE|os.O_EXCL, 666) | |
if err != nil { | |
if !os.IsExist(err) { | |
return err | |
} else { | |
return nil | |
} | |
} | |
return f.Close() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment