下面是我用来替换nagios.cfg中的200多个字符串的shell脚本。
我希望sed替换同一个文件中的所有200个字符串,而是复制内容200次,每次都有一次更改。
#set -x
cat partthree | while read LINE
do hostnam=`echo $LINE | awk '{print $1}'`
echo $hostnam
a=`less hosts | grep $hostnam -A5 | grep -i md5sum | awk '{print $2}'`
b=`less partthree | grep $hostnam | awk '{print $2}'`
echo $a
echo $b
sed "s/$a/$b/g" hosts >> sample
# sed "s/$a/$b/g" hosts > sample will change only last occurence
done
尝试直接使用sed -i“s / $ a / $ b / g”主机
@Expected output:
define host {
address sampleaddress
alias samplealaias
host_name samplealhostname
_md5sum def(with replaced string)
}
输出
define host {
address sampleaddress
alias samplealaias
host_name samplealaias
c8h(origanal string) def(string that is supposed to replace original c8h value)
}
答案 0 :(得分:1)
以下脚本应该完成这项工作。它从最初的hosts
文件开始,一个接一个地执行单独的替换。与原始脚本的主要区别在于替换结果不会附加到结果文件,而是在结果文件上就地应用(sed -i
)。
# start with 'sample' = 'hosts'
cp hosts sample
# perform replacements one after another in 'sample'
cat partthree | while read LINE ; do
hostnam=`echo $LINE | awk '{print $1}'`
a=`less hosts | grep $hostnam -A5 | grep -i md5sum | awk '{print $2}'`
b=`less partthree | grep $hostnam | awk '{print $2}'`
# modify 'sample' in-place
sed -i "s/$a/$b/g" sample
done