From 6325d7fef6d36efc026a08f699e3020b9b30560f Mon Sep 17 00:00:00 2001 From: "Zed A. Shaw" Date: Wed, 22 Oct 2025 15:40:55 -0400 Subject: [PATCH] Basic grep working, no recursive though. --- grep/.gitignore | 2 ++ grep/Makefile | 4 ++++ grep/go.mod | 3 +++ grep/main.go | 52 +++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 61 insertions(+) create mode 100644 grep/.gitignore create mode 100644 grep/Makefile create mode 100644 grep/go.mod create mode 100644 grep/main.go diff --git a/grep/.gitignore b/grep/.gitignore new file mode 100644 index 0000000..4b1092f --- /dev/null +++ b/grep/.gitignore @@ -0,0 +1,2 @@ +grep +grep.exe diff --git a/grep/Makefile b/grep/Makefile new file mode 100644 index 0000000..bea7546 --- /dev/null +++ b/grep/Makefile @@ -0,0 +1,4 @@ + + +build: + go build . diff --git a/grep/go.mod b/grep/go.mod new file mode 100644 index 0000000..a9538bf --- /dev/null +++ b/grep/go.mod @@ -0,0 +1,3 @@ +module lcthw.dev/go/go-coreutils/grep + +go 1.25.3 diff --git a/grep/main.go b/grep/main.go new file mode 100644 index 0000000..f1dc9e1 --- /dev/null +++ b/grep/main.go @@ -0,0 +1,52 @@ +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 [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) + } + } +}