Video Coming Soon...

Created by Zed A. Shaw Updated 2025-10-23 14:49:14

45: grep

This exercise is pending. Quick notes about this exercise:

The Code

View Source file go-coreutils/grep/main.go Only

package main

import (
  "fmt"
  "regexp"
  "os"
  "bufio"
  "flag"
  "log"
  "io"
)

func ScanInput(input io.Reader, exp string, prefix string) {
    scan := bufio.NewScanner(input)
    re, err := regexp.Compile(exp)

    if err != nil { log.Fatal(err) }

    for scan.Scan() {
        line := scan.Text()

        if re.MatchString(line) {
            if prefix != "" {
                fmt.Print(prefix, ": ")
            }

            fmt.Println(line)
        }
    }
}

func main() {
    flag.Parse()

    args := flag.Args()

    if len(args) == 0 {
        log.Fatal("USAGE: grep <regex> [files...]")
    } else if len(args) == 1 {
        ScanInput(os.Stdin, args[0], "")
    } else {
        exp := args[0]
        files := args[1:]

        for _, file := range files {
            input, err := os.Open(file)
            if err != nil { log.Fatal(err) }

            ScanInput(input, exp, file)
        }
    }
}
Previous Lesson Next Lesson

Register for Learn Go the Hard Way

Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.