Video Coming Soon...
46: find
This exercise is pending. Quick notes about this exercise:
- My implemention is at https://lcthw.dev/go/go-coreutils
- https://www.gnu.org/software/findutils/manual/html_mono/find.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/find/main.go Only
package main
import (
"fmt"
"flag"
"path/filepath"
"regexp"
"log"
"io/fs"
)
type Opts struct {
Name string
Type string
Print bool
}
func main() {
var opts Opts
flag.StringVar(&opts.Name, "name", "", "regex of file")
flag.StringVar(&opts.Type, "type", "f", "type to find")
flag.Parse()
re, err := regexp.Compile(opts.Name)
if err != nil { log.Fatal(err) }
if flag.NArg() == 0 {
log.Fatal("USAGE: find -name <regex> [-type d/f] <dir> [dir dir]")
}
for _, start := range flag.Args() {
filepath.WalkDir(start, func (path string, d fs.DirEntry, err error) error {
if re.MatchString(path) && opts.Print {
if opts.Type == "" {
fmt.Println(path)
} else if d.IsDir() && opts.Type == "d" {
fmt.Println(path)
} else if !d.IsDir() && opts.Type == "f" {
fmt.Println(path)
}
}
return nil
})
}
}
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.