-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
75 lines (66 loc) · 1.29 KB
/
main.go
File metadata and controls
75 lines (66 loc) · 1.29 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// uniq - filter out repeated lines in a file.
package main
import (
"solod.dev/so/bufio"
"solod.dev/so/flag"
"solod.dev/so/fmt"
"solod.dev/so/io"
"solod.dev/so/mem"
"solod.dev/so/os"
)
var showCount bool
func main() {
parseFlags()
args := flag.Args()
if len(args) == 0 || args[0] == "-" {
uniq(os.Stdin)
} else {
f, err := os.Open(args[0])
if err != nil {
fmt.Printf("uniq: %s: No such file or directory\n", args[0])
os.Exit(1)
}
uniq(&f)
f.Close()
}
}
// parseFlags parses command-line flags.
func parseFlags() {
flag.BoolVar(&showCount, "c", false, "count occurrences of each line")
flag.Parse()
}
// uniq writes the unique lines from r to standard output, optionally with counts.
func uniq(r io.Reader) {
scanner := bufio.NewScanner(mem.System, r)
defer scanner.Free()
prev := ""
hasPrev := false
count := 1
for scanner.Scan() {
line := scanner.Text()
if !hasPrev {
prev = line
hasPrev = true
count = 1
continue
}
if line == prev {
count++
} else {
printLine(prev, count)
prev = line
count = 1
}
}
if hasPrev {
printLine(prev, count)
}
}
// printLine prints a line with an optional count prefix.
func printLine(line string, count int) {
if showCount {
fmt.Printf("%4d %s\n", count, line)
} else {
fmt.Println(line)
}
}