批量重命名/删除文件

平时下载文件或者视频的命名很多带有长长的网址前缀,比如一些编程的教学视频,如果对其进行重命名观感上舒服多了;还有一些的压缩包,解压之后,文件夹中包含广告的网页文件,我们也希望对其进行删除。

批量重命名文件

package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "strings"
)

// updateFileName 重命名文件夹 dirname 中的文件,将 oldStr 字符串替换为 newStr
func updateFileName(dirPath, oldStr, newStr string) {
    fileInfos, err := ioutil.ReadDir(dirPath)
    if err != nil {
        return
    }

    for _, fileInfo := range fileInfos {
        filePath := dirPath + "\\" + fileInfo.Name()
        fmt.Println(filePath) // 打印文件地址
        if fileInfo.IsDir() {
            // 如果当前文件是文件夹,递归调用
            updateFileName(filePath, oldStr, newStr)
        } else {
            // 如果文件名包含 oldStr 字段,则将替换为 newStr
            if strings.Contains(fileInfo.Name(), oldStr) {
                err := os.Rename(filePath, dirPath+"\\"+strings.Replace(f.Name(), oldStr, newStr, -1))
                if err != nil {
                    panic(err)
                }
            }
        }
    }
}

func main() {
    // 重命名 test 文件夹下所有文件,将 "www.xxx.com" 替换为 ""
    updateFileName("C:\\xxx\\test", "www.xxx.com", "")
}

批量删除文件

package main

import (
    "fmt"
    "io/ioutil"
    "os"
)

// deleteFile 删除 dirPath 目录下的指定文件(fileNameSet)
func deleteFile(dirPath string, fileNameSet map[string]bool) {
    fileInfos, err := ioutil.ReadDir(dirPath)
    if err != nil {
        panic(err)
    }

    for _, fileInfo := range fileInfos {
        filePath := dirPath + "\\" + fileInfo.Name()
        fmt.Println(filePath) // 打印文件地址
        if fileInfo.IsDir() {
            // 如果当前文件是文件夹,递归调用
            deleteFile(filePath, fileNameSet)
        } else {
            // 删除指定文件
            if _, ok := fileNameSet[fileInfo.Name()]; ok {
                err := os.Remove(filePath)
                if err != nil {
                    panic(err)
                }
            }
        }
    }
}

func main() {
    // 删除 C:\xxx\test 目录下的所有 xxx.txt 文件
    fileNames := []string{"xxx.txt"}
    fileNameSet := make(map[string]bool, len(fileNames))
    for _, fileName := range fileNames {
        fileNameSet[fileName] = true
    }
    deleteFile("C:\\xxx\\test", fileNameSet)
}
posted @ 2022-05-26 15:38  呵呵233  阅读(303)  评论(0编辑  收藏  举报