Skip to content

Instantly share code, notes, and snippets.

@aln787
Last active January 20, 2023 22:05
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • 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
}
@asoorm
Copy link

asoorm commented Dec 31, 2017

This is not ideal solution imo... let's assume ext == .txt and filename is filename.txt.bak Then your regexp would still match. I would use filepath.Ext instead of regexp.

if filepath.Ext(path) == ext {
    files = append(files, f.Name())
}

@kudramh
Copy link

kudramh commented May 3, 2019

Thank you, It works for me as it is!

@largerock
Copy link

yee haw

@fourst4r
Copy link

do note that this ignores the filepath.Walk error and the regexp.MatchString error

@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