-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcat.go
72 lines (67 loc) · 1.44 KB
/
cat.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package main
import (
"bufio"
"flag"
"fmt"
"io"
"net"
"os"
)
var countNonBlank = flag.Bool("b", false, "Number the non-blank output lines, starting at 1.")
var numberOutput = flag.Bool("n", false, "Number the output lines, starting at 1.")
var squeezeEmptyLines = flag.Bool("s", false,
"Squeeze multiple adjacent empty lines, causing the output to be single spaced.")
func openFile(s string) (io.ReadWriteCloser, error) {
fi, err := os.Stat(s)
if err != nil {
return nil, err
}
if fi.Mode()&os.ModeSocket != 0 {
return net.Dial("unix", s)
}
return os.Open(s)
}
func dumpLines(w io.Writer, r io.Reader) (n int64, err error) {
var lastline, line string
br := bufio.NewReader(r)
nr := 0
for {
line, err = br.ReadString('\n')
if err != nil {
return
}
if *squeezeEmptyLines && lastline == "\n" && line == "\n" {
continue
}
if *countNonBlank && line == "\n" || line == "" {
fmt.Fprint(w, line)
} else if *countNonBlank || *numberOutput {
nr++
fmt.Fprintf(w, "%6d\t%s", nr, line)
} else {
fmt.Fprint(w, line)
}
lastline = line
}
return
}
func main() {
flag.Parse()
rcopy := io.Copy
if *countNonBlank || *numberOutput || *squeezeEmptyLines {
rcopy = dumpLines
}
for _, fname := range flag.Args() {
if fname == "-" {
rcopy(os.Stdout, os.Stdin)
} else {
f, err := openFile(fname)
defer f.Close()
if err != nil {
fmt.Fprintln(os.Stderr, err)
continue
}
rcopy(os.Stdout, f)
}
}
}