Created
July 11, 2015 11:50
-
-
Save iamralch/a95595069e560173a3c8 to your computer and use it in GitHub Desktop.
searchr - a sample application that works with pipes
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
package main | |
import ( | |
"bufio" | |
"flag" | |
"fmt" | |
"io" | |
"os" | |
"strings" | |
) | |
func main() { | |
pattern := flag.String("pattern", "", "Pattern definition to look for") | |
flag.Parse() | |
if *pattern == "" { | |
fmt.Println("Pattern argument is missing.") | |
fmt.Println("Usage:") | |
flag.PrintDefaults() | |
return | |
} | |
info, _ := os.Stdin.Stat() | |
if (info.Mode() & os.ModeCharDevice) == os.ModeCharDevice { | |
fmt.Println("The command is intended to work with pipes.") | |
fmt.Println("Usage:") | |
fmt.Println(" cat yourfile.txt | searchr -pattern=<your_pattern>") | |
} else if info.Size() > 0 { | |
reader := bufio.NewReader(os.Stdin) | |
match(*pattern, reader) | |
} | |
} | |
func match(pattern string, reader *bufio.Reader) { | |
line := 1 | |
for { | |
input, err := reader.ReadString('\n') | |
if err != nil && err == io.EOF { | |
break | |
} | |
color := "\x1b[39m" | |
if strings.Contains(input, pattern) { | |
color = "\x1b[31m" | |
} | |
fmt.Printf("%s%2d: %s", color, line, input) | |
line++ | |
} | |
} |
Why is this code not working for me? It seems that my info.Size() is always 0
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice!