Skip to content

Instantly share code, notes, and snippets.

@aln787
Last active January 20, 2023 22:05
Show Gist options
  • Save aln787/ea40d18cc33c7a983549 to your computer and use it in GitHub Desktop.
Save aln787/ea40d18cc33c7a983549 to your computer and use it in GitHub Desktop.
Go Lang find files with extension from the current working directory.
/* Go Lang find files with extension from the current working directory.
Copyright (c) 2010-2014 Alex Niderberg */
package main
import (
"fmt"
"os"
"path/filepath"
"regexp"
)
func main() {
fmt.Println(checkExt(".txt"))
}
func checkExt(ext string) []string {
pathS, err := os.Getwd()
if err != nil {
panic(err)
}
var files []string
filepath.Walk(pathS, func(path string, f os.FileInfo, _ error) error {
if !f.IsDir() {
r, err := regexp.MatchString(ext, f.Name())
if err == nil && r {
files = append(files, f.Name())
}
}
return nil
})
return files
}
@eksrha
Copy link

eksrha commented May 31, 2021

Nice thanks!

You can also write regex in the ext variable.
if you have a file with .txt.bak, you can just add a $ to the end. This means that the extension .txt must always be at the end and nothing more may come after it.

func main() {
	fmt.Println(checkExt(".txt$"))
}

Or for a more advanced selection:

# Files in Folder
my_nice.txt
my_second-nice.txt
my_nice.txt.bak
superduper.txt
func main() {
	fmt.Println(checkExt("my_.*.txt$"))
}

Output: [my_nice.txt my_second-nice]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment