batch_op_file/main.go

57 lines
1.3 KiB
Go
Raw Normal View History

2024-12-19 19:58:06 +08:00
package main
import (
"bytes"
"fmt"
"os"
"path/filepath"
)
func main() {
paths := getFiles(".")
for _, path := range paths {
// 读取文本格式的文件内容自动替换“fonts.googleapis.com”为“fonts.loli.net”“fonts.gstatic.com”为“fonts.loli.net”
content, err := os.ReadFile(path)
if err != nil {
fmt.Println("Error reading file:", err)
continue
}
content = bytes.ReplaceAll(content, []byte("fonts.googleapis.com"), []byte("fonts.loli.net"))
content = bytes.ReplaceAll(content, []byte("fonts.gstatic.com"), []byte("fonts.loli.net"))
os.WriteFile(path, content, 0644)
}
}
// 遍历当前目录以及子目录下所有文件,返回[]string绝对路径
func getFiles(rootPath string) []string {
var paths []string
var walkDir func(dirPath string) error
walkDir = func(dirPath string) error {
files, err := os.ReadDir(dirPath)
if err != nil {
return err
}
for _, file := range files {
fullPath := filepath.Join(dirPath, file.Name())
if file.IsDir() {
if err := walkDir(fullPath); err != nil {
return err
}
} else {
paths = append(paths, fullPath)
}
}
return nil
}
if err := walkDir(rootPath); err != nil {
fmt.Println("Error walking directory:", err)
return nil
}
return paths
}