box-o-sand/oldstuff/gotime/junkdrawer/greppish/main.go
2015-06-22 13:15:42 -05:00

52 lines
815 B
Go

package main
import (
"bufio"
"fmt"
"io"
"log"
"os"
"regexp"
)
const USAGE = `Usage: greppish <regex> [filename]
Prints lines matching <regex> in [filename] or standard input.`
func main() {
if len(os.Args) < 2 {
fmt.Println(USAGE)
os.Exit(1)
}
regMatch, err := regexp.Compile(os.Args[1])
if err != nil {
log.Fatal("Problem compiling regex: ", err)
}
inbuf := bufio.NewReader(os.Stdin)
if len(os.Args) > 2 {
infile, err := os.Open(os.Args[2])
if err != nil {
log.Fatal("Problem opening input file: ", err)
}
inbuf = bufio.NewReader(infile)
}
var line string
for {
line, err = inbuf.ReadString('\n')
if err != nil {
if err == io.EOF {
os.Exit(0)
}
log.Fatal("Problem reading input: ", err)
}
if regMatch.MatchString(line) {
fmt.Printf(line)
}
}
}