Last active
January 20, 2023 22:05
-
-
Save aln787/ea40d18cc33c7a983549 to your computer and use it in GitHub Desktop.
Go Lang find files with extension from the current working directory.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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 | |
} |
do note that this ignores the filepath.Walk
error and the regexp.MatchString
error
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
yee haw