// Grep searches the input file for lines containing the given pattern and // prints these lines. It is a simplified version of the Unix grep command. package main import ( "bufio" "fmt" "io" "log" "os" "strings" ) const prog = "grep" func init() { log.SetPrefix(prog + ": ") log.SetFlags(0) // no extra info in log messages } func main() { if len(os.Args) != 3 { log.Fatalf("usage: %s PATTERN FILE\n", prog) } pattern := os.Args[1] file, err := os.Open(os.Args[2]) if err != nil { log.Fatalln(err) } defer file.Close() if grep(pattern, file) != nil { log.Println(err) } } // grep prints all lines that contain the pattern. func grep(pattern string, file *os.File) error { reader := bufio.NewReader(file) for { switch line, err := reader.ReadString('\n'); err { case nil: grepLine(pattern, line) case io.EOF: if len(line) > 0 { // The final line of the file doesn't end with '\n'. grepLine(pattern, line) } return nil default: return err } } panic("internal error") } // grepLine prints the line if it contains the pattern. func grepLine(pattern, line string) { if strings.Contains(line, pattern) { fmt.Print(line) } }