使用shell 完成递归替换键值的作用?
背景
基于hw某项目的要求 提供了一套环境搭建的脚本 其中脚本提供了一个配置项的文件
里面定义了环境搭建过程过程中的诸多键值
现在华为说我之前定义的键不满足句意和规范 要修改 但是鉴于要求改的文件太多了且层级嵌套的深 决定使用shell脚本来完成.
要求
- 排除某些特定的文件夹
- 打印出要修改的行
- 简洁明了 可读性强 且健壮性高
自己尝试写了一个 感觉美中不足 求大佬优化
#!/usr/bin/env basheval $(cat hcs.setting.maps | awk 'BEGIN{printf "declare -A keyMap=("} END {print ")"} {printf "[\"%s\"]=\"%s\" " , $1,$2}')
declare -p keyMap
for key in $(echo ${!keyMap[@]})
do
value=${keyMap[${key}]}
echo "replace ${key} ==> $value"
echo
grep "${key}" -rl --exclude-dir={aarch64,x86_64} --exclude=*.{jpg,exe,gz} --exclude={hcs.setting.maps,automatichcskeyreplacementscript.sh} ./ | xargs grep "${key}" -n
echo "replaceing......"
grep "${key}" -rl --exclude-dir={aarch64,x86_64} --exclude=*.{jpg,exe,gz} --exclude={hcs.setting.maps,automatichcskeyreplacementscript.sh} ./ | xargs sed -i "s/${key}/$value/"
echo "replace ${key}"' ==> '"$value success!"
done
其中hcs.setting.maps
是我定义的 oldKey ==> newKey 的转换文本标准
OLDkEY NEWkEYSUPER MAN
APPLE PEAR
回答:
优化了一波
#!/bin/bashK=$(tput setaf 0)
R=$(tput setaf 1)
G=$(tput setaf 2)
Y=$(tput setaf 3)
B=$(tput setaf 4)
M=$(tput setaf 5)
C=$(tput setaf 6)
W=$(tput setaf 7)
# Use Q to revert color
Q=$(tput sgr0)
eval $(cat hcs.settings.maps | awk 'BEGIN{printf "declare -A keyMap=("} END {print ")"} {printf "[\"%s\"]=\"%s\" " , $1,$2}')
declare -p keyMap
for key in $(echo ${!keyMap[@]}); do
echo ${Q}
value=${keyMap[${key}]}
echo "${B}replace ${R}${key} ==> ${C}$value${Q}"
baseComputeSh="grep ${key} -rl --exclude-dir={aarch64,x86_64,.svn,04-document,05-sql,06-db} --exclude=*.{jpg,exe,gz} --exclude={hcs.settings.maps,automatichcskeyreplacementscript.sh} ./"
mathedNum=$(eval $baseComputeSh | wc -l)
echo
echo "${B}The matched $key values are ${R}$mathedNum"
echo
eval $baseComputeSh | xargs grep "${key}" -n --color
echo
echo "${G}=============================================="
echo "${M}High-speed replacement in progress, please wait"
echo "=============================================="
eval $baseComputeSh | xargs sed -i "s/${key}/$value/"
echo "${B}All attribute values ${G}$key ${B}have been completely replaced ${R}$value ${R}!${G}"
echo "=============================================="
done
以上是 使用shell 完成递归替换键值的作用? 的全部内容, 来源链接: utcz.com/p/944914.html