Skip to content

Instantly share code, notes, and snippets.

@iamralch
Created July 11, 2015 11:50
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save iamralch/a95595069e560173a3c8 to your computer and use it in GitHub Desktop.
Save iamralch/a95595069e560173a3c8 to your computer and use it in GitHub Desktop.
searchr - a sample application that works with pipes
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++
}
}
@ymgyt
Copy link

ymgyt commented Oct 7, 2017

nice!

@ChiliConSql
Copy link

ChiliConSql commented Jul 23, 2020

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