这两天用markdown写去年的总结,然后有很多的照片想加进来,发现一个个手写路径比较麻烦,而直接拖进来只有少数编辑器支持,而且一堆图片拖进来的话还是乱序,比较麻烦。

于是用go写了个小程序,可以将目录下的文件按模板输出,还可以选择批量加入指定字符做分隔行。

1
2
3
4
5
6
7
8
9
Usage of listdir:
-b string
blank line by
-bn int
blank line number
-f string
format: xxx___xxx
-p string
path (default "./")

比如我这里就是将目录里的图片全部格式化成markdown的语法,并且每个中间插入3行<br />做换行,然后输出到s.md中

1
listdir -f "\![](___)" -b "<br />" -bn 3 > s.md

代码如下,也在gist上也放了一份。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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)
}
}
}

Comments