From d0fbe716d955f90aad022bb0a1a923cbd0eac551 Mon Sep 17 00:00:00 2001 From: Dan Buch Date: Sat, 10 Nov 2012 20:27:23 -0500 Subject: [PATCH] Messing around with I/O streams and regexes --- gotime/Makefile | 4 ++ .../junkdrawer/greppish/main.go | 51 +++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 gotime/src/meatballhat.com/junkdrawer/greppish/main.go diff --git a/gotime/Makefile b/gotime/Makefile index d47f342..a3ea54b 100644 --- a/gotime/Makefile +++ b/gotime/Makefile @@ -4,6 +4,10 @@ PACKAGES := $(foreach pkg,\ $(shell ls src/meatballhat.com/gotour-artifacts),\ $(patsubst %,meatballhat.com/gotour-artifacts/%,$(pkg))\ ) +PACKAGES += $(foreach pkg,\ + $(shell ls src/meatballhat.com/junkdrawer),\ + $(patsubst %,meatballhat.com/junkdrawer/%,$(pkg))\ + ) PACKAGES += meatballhat.com/amqpfun-runner test: build diff --git a/gotime/src/meatballhat.com/junkdrawer/greppish/main.go b/gotime/src/meatballhat.com/junkdrawer/greppish/main.go new file mode 100644 index 0000000..da641fa --- /dev/null +++ b/gotime/src/meatballhat.com/junkdrawer/greppish/main.go @@ -0,0 +1,51 @@ +package main + +import ( + "bufio" + "fmt" + "io" + "log" + "os" + "regexp" +) + +const USAGE = `Usage: greppish [filename] + +Prints lines matching 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) + } + } +}