三种不同解决方案的比较
更小,使用sed
:
sed -e ':a;N;/\n#MyUniqueString/{s/\n/ domain4.com\n/};H;s/\n.*$//;p;g;s/^.*\n//;ta;' config.file
这可以运行为:
sed -e '
:a;
N;
/\n#MyUniqueString/{
s/\n/ domain4.com\n/
};
H;
s/\n.*$//;
p;
g;
s/^.*\n//;
ta;
' config.file
简介:
time sed ':a;N;/\n#MyUniqueString/{s/\n/ domain4.com\n/};H;
s/\n.*$//;p;g;s/^.*\n//;ta;' config.file
define hostgroup{
hostgroup_name http-urls ; The name of the hostgroup
alias HTTP URLs ; Long name of the group
members domain1.com, domain2.com, domain3.com, domain4.com
#MyUniqueString
}
real 0m0.010s
user 0m0.000s
sys 0m0.008s
为什么不是纯 bash?
由于没有 fork,这可能非常快(如果来自bash
并且不是太长的配置文件):
readarray configFile < ./config.file
for ((i=${#configFile};i--;));do
[[ "${configFile[i]}" =~ "#MyUniqueString" ]] && break
done
configFile[i-1]+=" domain4.com"
printf "%s\n" "${configFile[@]//$'\n'/}"
分析运行:
time {
readarray configFile < ./config.file
for ((i=${#configFile};i--;));do
[[ "${configFile[i]}" =~ "#MyUniqueString" ]] && break
done
configFile[i-1]+=" domain4.com"
printf "%s\n" "${configFile[@]//$'\n'/}"
}
会给:
define hostgroup{
hostgroup_name http-urls ; The name of the hostgroup
alias HTTP URLs ; Long name of the group
members domain1.com, domain2.com, domain3.com, domain4.com
#MyUniqueString
}
real 0m0.001s
user 0m0.000s
sys 0m0.000s
测试awk
time awk '{a[NR]=$0}/#MyUniqueString/{a[NR-1]=a[NR-1]" domain4.com"}END{for(i=1;i<=NR;i++)print a[i]}' config.file
define hostgroup{
hostgroup_name http-urls ; The name of the hostgroup
alias HTTP URLs ; Long name of the group
members domain1.com, domain2.com, domain3.com, domain4.com
#MyUniqueString
}
real 0m0.009s
user 0m0.004s
sys 0m0.000s