-
Notifications
You must be signed in to change notification settings - Fork 1
/
sort_lines_in_files.go
48 lines (44 loc) · 1.2 KB
/
sort_lines_in_files.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// -----------------------------------------------------------------------------
// CMDX Utilities Suite cmdx/[sort_lines_in_files.go]
// (c) [email protected] License: GPLv3
// -----------------------------------------------------------------------------
package main
import (
"sort"
"strings"
)
// sortFileLines sorts all the lines in the specified file, removing
// non-unique lines. This command can be used to keep log files sorted.
func sortFileLines(cmd Command, args []string) {
if len(args) != 1 {
env.Println("requires <file-name> parameter")
return
}
// read the file
var (
filename = args[0]
lines = env.ReadFileLines(filename)
oldContent = strings.Join(lines, "\n")
)
// remove non-unique lines
if true {
unique := make(map[string]bool, len(lines))
for _, line := range lines {
unique[line] = true
}
lines = make([]string, 0, len(unique))
for key := range unique {
lines = append(lines, key)
}
}
// sort the lines
sort.Strings(lines)
//
// don't save if nothing changed
if strings.Join(lines, "\n") == oldContent {
return
}
// save the file
env.WriteFileLines(filename, lines)
}
// end