本文目录导读:

当然可以!批量递归处理是脚本中非常常见的需求,很多实用脚本都能实现递归操作,这里我给你介绍几种常见场景下的递归脚本方案:
Shell/bash 递归脚本
批量修改文件扩展名(递归遍历所有子目录)
#!/bin/bash
# 递归将 .txt 改为 .md
recursive_rename() {
local dir="$1"
find "$dir" -type f -name "*.txt" | while read file; do
mv "$file" "${file%.txt}.md"
echo "已修改: $file"
done
}
recursive_rename "/path/to/directory"
批量替换文件内容(递归所有子目录)
#!/bin/bash
# 递归替换文件中的字符串
recursive_replace() {
local dir="$1"
local old_string="$2"
local new_string="$3"
find "$dir" -type f \( -name "*.txt" -o -name "*.md" \) | while read file; do
sed -i "s/$old_string/$new_string/g" "$file"
echo "已处理: $file"
done
}
recursive_replace "./project" "旧内容" "新内容"
Python 递归脚本
批量处理图片尺寸(递归所有子目录)
import os
from PIL import Image
import sys
def resize_images_recursive(root_dir, target_width=800):
for root, dirs, files in os.walk(root_dir):
for file in files:
if file.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')):
filepath = os.path.join(root, file)
try:
img = Image.open(filepath)
width_percent = target_width / float(img.size[0])
new_height = int(float(img.size[1]) * float(width_percent))
img = img.resize((target_width, new_height), Image.Resampling.LANCZOS)
img.save(filepath)
print(f"已缩放: {filepath}")
except Exception as e:
print(f"处理失败 {filepath}: {e}")
resize_images_recursive("/path/to/images")
批量压缩文件夹(递归压缩每个子文件夹)
import os
import zipfile
import shutil
def zip_subdirectories_recursive(root_dir):
for item in os.listdir(root_dir):
item_path = os.path.join(root_dir, item)
if os.path.isdir(item_path):
zip_name = f"{item_path}.zip"
with zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED) as zipf:
for root, dirs, files in os.walk(item_path):
for file in files:
file_path = os.path.join(root, file)
arcname = os.path.relpath(file_path, root_dir)
zipf.write(file_path, arcname)
print(f"已压缩: {item_path} -> {zip_name}")
shutil.rmtree(item_path) # 可选:删除原文件夹
zip_subdirectories_recursive("/path/to/directory")
Node.js (JavaScript) 递归脚本
批量处理 JSON 文件(递归所有子目录)
const fs = require('fs');
const path = require('path');
function processJSONFilesRecursively(dir) {
const files = fs.readdirSync(dir);
files.forEach(file => {
const filepath = path.join(dir, file);
const stat = fs.statSync(filepath);
if (stat.isDirectory()) {
processJSONFilesRecursively(filepath); // 递归调用
} else if (file.endsWith('.json')) {
try {
const content = fs.readFileSync(filepath, 'utf8');
const data = JSON.parse(content);
// 处理 JSON 数据...
data.processed = true;
data.timestamp = new Date().toISOString();
fs.writeFileSync(filepath, JSON.stringify(data, null, 2));
console.log(`已处理: ${filepath}`);
} catch(err) {
console.error(`处理失败 ${filepath}: ${err.message}`);
}
}
});
}
processJSONFilesRecursively('./data');
实用小技巧
安全执行递归(避免误操作)
#!/bin/bash
safe_recursive_execute() {
local dir="$1"
# 先预览要处理的内容
echo "将要处理的路径:"
find "$dir" -type f -name "*.log" -mtime +7
echo "是否继续? (y/n): "
read confirm
if [ "$confirm" = "y" ]; then
find "$dir" -type f -name "*.log" -mtime +7 -delete
echo "已删除30天前的日志文件"
else
echo "已取消操作"
fi
}
safe_recursive_execute "/var/log"
注意事项
- 性能优化:处理大量文件时,
find命令比递归循环更快 - 权限检查:递归操作前检查文件权限
- 备份策略:重要操作前先备份
- 限速处理:处理海量文件时添加延迟,避免系统负载过高
find . -type f | while read file; do # 处理文件 sleep 0.1 # 延迟100ms done
这些脚本都能实现批量递归操作,你可以根据具体需求选择或修改使用,需要更具体的场景脚本吗?