我的示例文件如下:
# sample.txt
adc=lalalala
cmd="echo hihi && echo yoyo"
cda=lolololo
我希望替换cmd
的行,如:
old=`cat ./sample.txt|grep cmd`
app=' && echo dudu"'
new=${old:0:-1}${app}
sed -i "s/${old}/${new}/g" ./sample.txt
期望的结果应该是
adc=lalalala
cmd="echo hihi && echo yoyo && echo dudu"
cda=lolololo
无论结果如何:
adc=lalalala
cmd="echo hihi cmd="echo hihi && echo yoyo"cmd="echo hihi && echo yoyo" echo yoyo cmd="echo hihi && echo yoyo"cmd="echo hihi && echo yoyo" echo dudu"
cda=lolololo
我也尝试了sed -i "s#${old}#${new}#g" ./sample.txt
,但没有差异。能帮我一下吗?非常感谢
试试
sed -E -i '' 's@(cmd="echo hihi && echo yoyo)"@1 && echo dudu"@' sample.txt
注意你必须逃离&
。
键的变化应该是:
sed -i "/^cmd=*/c$new" ./sample.txt
完整的shell脚本如下:
old=`cat ./sample.txt|grep cmd`
app=' && echo dudu"'
new=${old:0:-1}${app}
sed -i "/^cmd=*/c$new" ./sample.txt