Video Coming Soon...
45: grep
This exercise is pending. Quick notes about this exercise:
- My implemention is at https://lcthw.dev/go/go-coreutils
- https://www.gnu.org/software/grep/manual/html_node/index.html
- os -- https://pkg.go.dev/os@go1.25.3
- path -- probably all of them use it
- regex -- https://pkg.go.dev/regexp@go1.25.3
- slices -- https://pkg.go.dev/slices@go1.25.3
- strings -- https://pkg.go.dev/strings@go1.25.3
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)
}
}
}
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.