Last active
January 9, 2016 15:28
-
-
Save supercocoa/10fb7b81ae3853108ec1 to your computer and use it in GitHub Desktop.
listdir by go. support format and insert some strings for blank line.
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
package main | |
import ( | |
"flag" | |
"fmt" | |
"io/ioutil" | |
"path/filepath" | |
"sort" | |
"strconv" | |
"strings" | |
) | |
const ( | |
//PATTERN format by this pattern | |
PATTERN = "___" | |
) | |
var path = flag.String("p", "./", "path") | |
var format = flag.String("f", "", "format: xxx"+PATTERN+"xxx") | |
var blankLine = flag.String("b", "", "blank line by") | |
var blankLineNum = flag.Int("bn", 0, "blank line number") | |
var sortByNum = flag.Bool("sn", true, "sort by num") | |
type ByNum []string | |
func (paths ByNum) Len() int { | |
return len(paths) | |
} | |
func (paths ByNum) Swap(i, j int) { | |
paths[i], paths[j] = paths[j], paths[i] | |
} | |
func (paths ByNum) Less(i, j int) bool { | |
pathi := filepath.Base(paths[i]) | |
pathj := filepath.Base(paths[j]) | |
namei := strings.Split(pathi, ".")[0] | |
namej := strings.Split(pathj, ".")[0] | |
numi, _ := strconv.Atoi(namei) | |
numj, _ := strconv.Atoi(namej) | |
return numi < numj | |
} | |
func listDir(path *string) []string { | |
files, _ := ioutil.ReadDir(*path) | |
fileSlice := make([]string, len(files)) | |
absPath, _ := filepath.Abs(*path) | |
for i, file := range files { | |
fileSlice[i] = absPath + "/" + file.Name() | |
} | |
if *sortByNum { | |
sort.Sort(ByNum(fileSlice)) | |
} else { | |
sort.Strings(fileSlice) | |
} | |
return fileSlice | |
} | |
func formatStr(str *string) *string { | |
if len(*format) > 0 && strings.Contains(*format, PATTERN) { | |
replace := strings.Replace(*format, PATTERN, *str, -1) | |
return &replace | |
} | |
return str | |
} | |
func main() { | |
flag.Parse() | |
rets := listDir(path) | |
var ret string | |
for i := 0; i < len(rets); i++ { | |
ret = rets[i] | |
fmt.Println(*(formatStr(&ret))) | |
if i == len(rets)-1 { | |
break | |
} | |
for i := 0; i < *blankLineNum; i++ { | |
fmt.Println(*blankLine) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment