Golang

关注公众号 jb51net

关闭
首页 > 脚本专栏 > Golang > Go文件管理工具

使用Go语言开发一个命令行文件管理工具

作者:白僧

这篇文章主要为大家详细介绍了如何使用Go语言开发一款命令行文件管理工具,支持批量重命名,删除,创建,移动文件,需要的小伙伴可以了解下

导语

还在为繁琐的文件操作烦恼吗?今天教你用Go语言开发一款命令行文件管理工具,支持批量重命名、删除、创建、移动文件,解放双手,提升效率!文末附完整源码,建议收藏!

一、工具功能一览

二、核心代码解析

1. 主程序结构

func main() {
    // 定义子命令
    renameCmd := flag.NewFlagSet("rename", flag.ExitOnError)
    deleteCmd := flag.NewFlagSet("delete", flag.ExitOnError)
    createCmd := flag.NewFlagSet("create", flag.ExitOnError)
    moveCmd := flag.NewFlagSet("move", flag.ExitOnError)

    // 解析命令行参数
    switch os.Args[1] {
    case "rename":
        renameCmd.Parse(os.Args[2:])
        renameFiles(*renamePattern, *renameReplacement)
    case "delete":
        deleteCmd.Parse(os.Args[2:])
        deleteFiles(*deletePattern)
    case "create":
        createCmd.Parse(os.Args[2:])
        createFileOrDir(*createPath, *createIsDir)
    case "move":
        moveCmd.Parse(os.Args[2:])
        moveFiles(*moveSource, *moveTarget)
    default:
        fmt.Println("Expected subcommands: rename, delete, create, or move")
        os.Exit(1)
    }
}

2. 批量重命名

func renameFiles(pattern, replacement string) {
    regex, err := regexp.Compile(pattern)
    if err != nil {
        log.Fatalf("Invalid regex pattern: %v", err)
    }

    filepath.Walk(".", func(path string, info os.FileInfo, err error) error {
        if regex.MatchString(info.Name()) {
            newName := regex.ReplaceAllString(info.Name(), replacement)
            newPath := filepath.Join(filepath.Dir(path), newName)
            fmt.Printf("Renaming %s to %s\n", path, newPath)
            return os.Rename(path, newPath)
        }
        return nil
    })
}

使用示例

# 将所有.txt文件重命名为.md
go run main.go rename -pattern="\.txt$" -replace=".md"

3. 批量删除

func deleteFiles(pattern string) {
    regex, err := regexp.Compile(pattern)
    if err != nil {
        log.Fatalf("Invalid regex pattern: %v", err)
    }

    filepath.Walk(".", func(path string, info os.FileInfo, err error) error {
        if regex.MatchString(info.Name()) {
            fmt.Printf("Deleting %s\n", path)
            return os.Remove(path)
        }
        return nil
    })
}

使用示例

# 删除所有.log文件
go run main.go delete -pattern="\.log$"

4. 创建文件/目录

func createFileOrDir(path string, isDir bool) {
    if isDir {
        err := os.MkdirAll(path, 0755)
        if err != nil {
            log.Fatalf("Error creating directory: %v", err)
        }
        fmt.Printf("Created directory: %s\n", path)
    } else {
        file, err := os.Create(path)
        if err != nil {
            log.Fatalf("Error creating file: %v", err)
        }
        defer file.Close()
        fmt.Printf("Created file: %s\n", path)
    }
}

使用示例

# 创建目录
go run main.go create -path="new_dir" -dir

# 创建文件
go run main.go create -path="new_file.txt"

5. 批量移动

func moveFiles(sourcePattern, targetDir string) {
    regex, err := regexp.Compile(sourcePattern)
    if err != nil {
        log.Fatalf("Invalid regex pattern: %v", err)
    }

    os.MkdirAll(targetDir, 0755)

    filepath.Walk(".", func(path string, info os.FileInfo, err error) error {
        if regex.MatchString(info.Name()) {
            newPath := filepath.Join(targetDir, info.Name())
            fmt.Printf("Moving %s to %s\n", path, newPath)
            return os.Rename(path, newPath)
        }
        return nil
    })
}

使用示例

# 将所有.jpg文件移动到images目录
go run main.go move -source="\.jpg$" -target="images"

三、如何安装使用

安装Go环境(参考前文教程)

编译运行

go build -o file-manager
./file-manager [command] [flags]

以上就是使用Go语言开发一个命令行文件管理工具的详细内容,更多关于Go文件管理工具的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文