Search code examples
regexgounixgrepgo-flag

How do i open all files of the format "test*.txt" in golang


If I give a flag (in golang) as 'test*.txt' (as a CLI argument), I need to open all files of the said format (example: test.txt, test1.txt, test2.txt).

I am thinking of doing a regex match with all the files present in the folder. Is there a better way?


Solution

  • You can use the filepath.Glob function:

    package main
    
    import (
        "fmt"
        "path/filepath"
    )
    
    func main() {
        matches, _ := filepath.Glob("test*.txt")
        for _, p := range matches {
            fmt.Println(p)
        }
    }