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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.Or for a more advanced selection:
# Files in Folder my_nice.txt my_second-nice.txt my_nice.txt.bak superduper.txt
Output:
[my_nice.txt my_second-nice]