如何在Bash中实现类似Python的字典键值替换文件内容功能?
在Bash中实现字典键值批量替换文本内容
没问题!在Bash里完全可以实现类似Python那种基于字典键值对批量替换文本内容的功能,我给你两种实用的方案,适配你的需求场景:
方案1:Bash循环 + sed(直观易理解)
这种方式和你Python里的循环替换逻辑最接近,通过遍历关联数组的键值对,用sed逐个完成全局替换。
步骤代码
# 1. 定义你的替换字典(关联数组,键是要替换的字符串,值是目标内容) declare -A replacements=( ['${!dictionary[i]}']=': for i in ...' ['${dictionary[i]}']='' ['addMesh:"0x234544"']='addMesh:"0x234544x0"' ['addMesh="0x12353514"']='addMesh="0x12353514x0"' ) # 2. 指定输入/输出文件(建议先备份原文件,避免误操作) input_file="input.txt" output_file="output.txt" cp "$input_file" "$output_file" # 复制原文件作为替换基础 # 3. 循环遍历字典,执行全局替换 for key in "${!replacements[@]}"; do value="${replacements[$key]}" # 转义sed特殊字符(/ 和 &),避免替换出错 escaped_key=$(printf '%s' "$key" | sed 's/[\/&]/\\&/g') escaped_value=$(printf '%s' "$value" | sed 's/[\/&]/\\&/g') # 执行替换,-i.bak会生成备份文件,替换后可删除 sed -i.bak "s/${escaped_key}/${escaped_value}/g" "$output_file" rm "${output_file}.bak" # 移除备份(不需要的话可以保留) done
方案2:Awk批量替换(高效适合大文件)
如果你的文件很大,循环调用sed会比较慢,用Awk可以一次性完成所有替换,效率更高。
步骤代码
# 1. 同样定义替换字典 declare -A replacements=( ['${!dictionary[i]}']=': for i in ...' ['${dictionary[i]}']='' ['addMesh:"0x234544"']='addMesh:"0x234544x0"' ['addMesh="0x12353514"']='addMesh="0x12353514x0"' ) # 2. 生成Awk可识别的映射脚本 awk_script='BEGIN {' for key in "${!replacements[@]}"; do awk_script+="map[\"$key\"]=\"${replacements[$key]}\";" done awk_script+='} { # 遍历所有映射规则,全局替换 for (k in map) { gsub(k, map[k]) } print $0 }' # 3. 执行替换并输出结果 awk "$awk_script" input.txt > output.txt
验证结果
假设你的input.txt内容为:
file= "addMesh:"0x234544" addMesh="0x12353514" ${!dictionary[i]}: 0x234544 ${dictionary[i]}: 0x234544x0 ${!dictionary[i]}: 0x12353514 ${!dictionary[i]}: 0x12353514x0
执行任意方案后,output.txt会得到你期望的输出:
file= "addMesh:"0x234544x0" addMesh="0x12353514x0" : for i in ...: 0x234544 : 0x234544x0 : for i in ...: 0x12353514 : for i in ...: 0x12353514x0
内容的提问来源于stack exchange,提问作者DuckDuckOverflow
相关产品推荐
相关产品推荐

