Cri*_*sta 2 unix bash replace sed
我对脚本性能感到厌倦.
基本上我必须在35000多个文件中替换600个字符串.
我有这样的事情:
patterns=(
oldText1 newText1
oldText2 newText2
oldText3 newText3
)
pattern_count=${#patterns[*]}
files=(`find \. -name '*.js'`);
files_count=${#files[*]}
for ((i=0; i < $pattern_count ; i=i+2)); do
search=${patterns[i]};
replace=${patterns[i+1]};
echo -en "\e[0K\r Status "$proggress"%. Iteration: "$i" of " $pattern_count;
for ((j=0; j < $files_count; j++)); do
command sed -i s#$search#$replace#g ${files[j]};
proggress=$(($i*100/$files_count));
echo -en "\e[0K\r Inside the second loop: " $proggress"%. File: "$j" of "$files_count;
done
proggress=$(($i*100/$pattern_count));
echo -en "\e[0K\r Status "$proggress"%. Iteration: "$i" of " $pattern_count;
done
Run Code Online (Sandbox Code Playgroud)
但这需要几分钟.有另一种解决方案吗?可能只使用sed一次而不是双循环?
非常感谢.
创建一个合适的sed
脚本:
s/pattern1/replacement1/g
s/pattern2/replacement2/g
...
Run Code Online (Sandbox Code Playgroud)
使用sed -f script.sed file
(或以任何方式)运行此脚本.
您可以sed
使用您的数组创建该脚本:
printf 's/%s/%s/g\n' "${patterns[@]}" >script.sed
Run Code Online (Sandbox Code Playgroud)
将其应用于文件:
find . -type f -name '*.js' -exec sed -i -f script.sed {} ';'
Run Code Online (Sandbox Code Playgroud)
我不太清楚sed
你使用GNU (我假设你正在使用)是如何处理多个文件的-i
,但你可能也想尝试一下
find . -type f -name '*.js' -exec sed -i -f script.sed {} +
Run Code Online (Sandbox Code Playgroud)
这可能会更有效(执行尽可能少的sed
命令).与往常一样,测试您可以在测试后丢弃的数据.
有关使用的详细信息-exec
与find
,看到https://unix.stackexchange.com/questions/389705