获取工具
源码在最下面
linux
wget www.zhanghaobk.com:81/Go/linux/zhfix && chmod +x zhfix && mv zhfix /usr/bin/
其他操作系统:点击查看下载
用法:
> zhfix -h
Usage zhfix: zhfix -d Dir -o oldFix -n newFIX
-R -- recursion: Recursive modified (default: false)
-d -- directoryPath: Directory path
-o -- oldPath: Old suffix
-n -- newFix: New suffix
-h -- help: help info
Example: Change JPG suffix in dir directory to JPG
zhfix -d dir -o JPG -n jpg -R
-R 递归修改
-d 目录路径
-o 旧的后缀
-n 新的后缀
linux试例:
//递归修改当前路径JPG结尾的修改为jpg
zhfix -d . -o JPG -n jpg -R
win使用如下图所示:
下面对比下go 和shell 的速度
#!/bin/bash
for i in `find . -name "*.JPG"`
do
mv $i ${i%JPG}jpg
done
这里写一个脚本,分别创建200个以JPG结尾的文件,创建目录1在目录1下创建200个JPG结尾的文件,然后分别运行go, 和shell脚本计算时间差
#!/bin/bash
rm -f *.jpg && rm -rf 1
touch {1..200}.JPG && mkdir 1 && touch 1/{1..200}.JPG
start_time=$[$(date +%s%N)/1000000]
./zhfix -d ./ -o JPG -n jpg -R #./为当前路径
end_time=$[$(date +%s%N)/1000000]
echo go执行时间为: $[end_time - start_time] 毫秒
rm -f *.jpg && rm -rf 1
touch {1..200}.JPG && mkdir 1 && touch 1/{1..200}.JPG
start2_time=$[$(date +%s%N)/1000000]
bash t.sh
end2_time=$[$(date +%s%N)/1000000]
echo shell执行时间为: $[end2_time - start2_time] 毫秒
如下图所示,go还是非常快的
下面是源码
zhfix.go
package main
import (
"flag"
"fmt"
"os"
"path"
"strings"
)
func walk(dirPath, oldFix, newFix string, R bool) error {
if subFile, err := os.ReadDir(dirPath); err != nil {
return fmt.Errorf("read Dir %s error: %s", dirPath, err)
} else {
for _, file := range subFile {
if file.IsDir() && R {
//walk(dirPath + "/" + file.Name())
//适应不同操作系统
walk(path.Join(dirPath, file.Name()), oldFix, newFix, R)
}
//fmt.Println(dirPath + "/" + file.Name())
//适应不同操作系统
//fmt.Println(path.Join(dirPath, file.Name()))
if path.Ext(file.Name()) == "."+oldFix {
oldPath := path.Join(dirPath, file.Name())
newName := strings.Replace(file.Name(), oldFix, newFix, 1)
newPath := path.Join(dirPath, newName)
err = os.Rename(oldPath, newPath)
if err != nil {
return err
}
}
}
}
return nil
}
//自定义使用函数
func usage() {
fmt.Printf(`Usage zhfix: zhfix -d Dir -o oldFix -n newFIX
-R -- recursion: Recursive modified (default: false)
-d -- directoryPath: Directory path
-o -- oldPath: Old suffix
-n -- newFix: New suffix
-h -- help: help info
Example: Change JPG suffix in dir directory to JPG
zhfix -d dir -o JPG -n jpg -R`)
fmt.Println()
}
func main() {
dirPath := flag.String("d", "", "p -- dirPath")
oldFix := flag.String("o", "", "o -- oldPath")
newFix := flag.String("n", "", "n -- newFix")
R := flag.Bool("R", false, "R -- recursion")
flag.Usage = usage
//解析获取参数值
flag.Parse()
if *dirPath == "" || *oldFix == "" || *newFix == "" {
usage()
} else {
if err := walk(*dirPath, *oldFix, *newFix, *R); err != nil {
fmt.Println(err)
}
}
}