根据某个关键词批量替换目录下的文件并显示执行进度情况的sh脚本

艺帆风顺 发布于 2025-04-03 18 次阅读


一、基本信息

    使用 find 和 sed 命令来批量替换 /usr 目录下包含字符串 “https://github.com/pengzhile/pandora” 的内容为 “https://www.gov.cn”。下面是一个示例脚本,可以显示替换进度情况和被替换的文件名:

、脚本内容

#!/bin/bash
# 定义要查找的目录search_dir="/usr"
# 定义要查找的字符串search_str="https://github.com/pengzhile/pandora"
# 定义要替换的字符串replace_str="https://www.gov.cn"
# 计算文件总数total_files=$(find "$search_dir" -type f | wc -l)
# 初始化计数器count=0
# 查找并替换文件内容while IFS= read -r -d '' file; do # 更新计数器 ((count++))
# 显示进度情况 printf "Progress: %d/%d (%.2f%%)n" "$count" "$total_files" "$(echo "$count/$total_files*100" | bc -l)"
# 显示被替换的文件名 echo "Replacing file: $file"
# 替换文件内容 sed -i "s#$search_str#$replace_str#g" "$file"done "$search_dir" -type f -exec grep -lZ "$search_str" {} +)