You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

52 lines
815 B

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)
}
}
}