개발/일상
[golang] List the files with extension in a directory
clucle
2021. 5. 24. 17:43
폴더 내에 있는 특정 확장자 전체 출력하기
Usage : go run main.go [path] [ext]
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
)
// https://gist.github.com/ivanzoid/129460aa08aff72862a534ebe0a9ae30#gistcomment-3733302
func fileNameWithoutExtension(fileName string) string {
if pos := strings.LastIndexByte(fileName, '.'); pos != -1 {
return fileName[:pos]
}
return fileName
}
func main() {
if len(os.Args) != 3 {
fmt.Println("Usage : go run main.go [path] [ext]")
return
}
path := os.Args[1]
ext := os.Args[2]
files, err := ioutil.ReadDir(path)
if err != nil {
log.Fatal(err)
}
for _, f := range files {
if filepath.Ext(f.Name()) == "."+ext {
fmt.Println(fileNameWithoutExtension((f.Name())))
}
}
}

