-
Notifications
You must be signed in to change notification settings - Fork 0
/
splitstr.go
56 lines (46 loc) · 1.01 KB
/
splitstr.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
package main
import (
"fmt"
"os"
"flag"
"bufio"
"strings"
)
func main() {
if false == isPipeline() {
fmt.Println("This command can only be used with pipelines.")
return
}
delimiter := flag.String("d", " ", "Delimiter: Used to split input. Defaults to whitespace")
index := flag.Int("i", 0, "Index: Print only the values from this index.")
s := bufio.NewScanner(os.Stdin)
for s.Scan() {
str := s.Text()
flag.Parse()
out := strings.Split(str, *delimiter)
if isFlagPassed("i") {
if *index < 0 || *index >= len(out) {
fmt.Printf("Only %v item(s) in input. -i should be between 0 and %v\n", len(out), len(out) -1)
return
}
fmt.Println(out[*index])
} else {
for _, e := range out {
fmt.Println(e)
}
}
}
}
func isPipeline() bool {
fileInfo, _ := os.Stdin.Stat()
return fileInfo.Mode() & os.ModeCharDevice == 0
}
func isFlagPassed(name string) bool {
r := false
flag.Visit(func(f *flag.Flag) {
if f.Name == name {
r = true
}
})
return r
}