Golang 清理本地图床中所有未被引用的图片

2023-05-16

背景

除了博客以外,我还有一些笔记存在 https://github.com/HanquanHq/MD-Notes 上了。在用 typora 的时候,图片都默认自动存到一个本地的文件夹里了,有时候粘贴的时候,回自动保存图片,后来内容删了,图片被留下了,相当于产生了一堆”需要回收的垃圾“,所以我们来手动清理下。

代码

package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"regexp"
	"strings"
)

func IsExist(str string, filepath string) bool {
	b, _ := ioutil.ReadFile(filepath)
	isExist, _ := regexp.Match(str, b)
	return isExist
}

func getNameList(path string) []string {
	var list []string
	filepath.Walk(path,
		func(path string, info os.FileInfo, err error) error {
			list = append(list, info.Name())
			return nil
		})
	return list
}

func getPathList(path string) []string {
	var list []string
	filepath.Walk(path,
		func(path string, info os.FileInfo, err error) error {
			if strings.HasSuffix(path, ".md") {
				list = append(list, path)
			}
			return nil
		})
	return list
}

func main() {
	rootPath := "/Users/bytedance/workspace/MD-Notes/"
	imgPath := "/Users/bytedance/workspace/MD-Notes/docs/images/"

	noteList := getPathList(rootPath)
	imgList := getNameList(imgPath)

	for _, img := range imgList {
		exist := false
		for _, note := range noteList {
			if IsExist(img, note) {
				exist = true
				break
			}
		}
		if !exist {
			fmt.Println("图片未被引用:", imgPath+img)
			err := os.Remove(imgPath + img)
			if err != nil {
				fmt.Println(err)
				return
			}
		}
	}

}

效果

找到并删除了10+个未被引用的图片,总共节省了 9MB 存储空间。
在这里插入图片描述

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Golang 清理本地图床中所有未被引用的图片 的相关文章

  • px4初级视频

    链接 xff1a https pan baidu com s 1VIQcOQt I5 evMx1jnV0ZQ 提取码 xff1a 8niq

随机推荐