Video Coming Soon...

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

46: find

This exercise is pending. Quick notes about this exercise:

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
        })
    }
}
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.