替换.conf文件中的整行

时间:2015-01-08 14:54:11

标签: bash sed dnsmasq

我有一种情况,我想要一个bash脚本来替换dnsmasq.conf中的整行

默认情况下,行为:

listen-address=192.168.42.1
dhcp-range=192.168.42.1,192.168.42.253,255.255.255.0,192.168.42.255,24h
dhcp-option=option:router,192.168.42.1

我实施:

new_ip=$1
broadcast=$2
base_ip=`echo $new_ip | cut -d"." -f1-3`

sed -i 's/^listen-address.*/listen-address=$new_ip/' /etc/dnsmasq.conf
sed -i 's/^dhcp-range.*/dhcp-range=$base_ip.1,$base_ip.254,255.255.255.0,$broadcast,24h/' /etc/dnsmasq.conf
sed -i 's/^dhcp-option.*/dhcp-option=option:router,$new_ip/' /etc/dnsmasq.conf

我将bash称为./test.sh 172.24.239.40 172.24.239.255,我获得以下几行:

listen-address=$new_ip
dhcp-range=$base_ip.1,$base_ip.254,255.255.255.0,$broadcast,24h
dhcp-option=option:router,$new_ip

是否可以在sed命令行中将参数与文本分离?

2 个答案:

答案 0 :(得分:1)

您可以使用:

sed -i.bak -e "s/^listen-address.*/listen-address=$new_ip/" \
 -e "s/^dhcp-range.*/dhcp-range=$base_ip.1,$base_ip.254,255.255.255.0,$broadcast,24h/" \
 -e "s/^dhcp-option.*/dhcp-option=option:router,$new_ip/" /etc/dnsmasq.conf

  • 使用双引号而不是单引号来允许变量展开
  • 单sed 中使用多个替换命令,而不是多次调用sed
  • 使用-i.bak通过.bak扩展名
  • 保护原始文件的安全

答案 1 :(得分:1)

如果在sed中有变量,请使用双引号而不是单引号:

sed -i "s/^listen-address.*/listen-address=$new_ip/" /etc/dnsmasq.conf
sed -i "s/^dhcp-range.*/dhcp-range=$base_ip.1,$base_ip.254,255.255.255.0,$broadcast,24h/" /etc/dnsmasq.conf
sed -i "s/^dhcp-option.*/dhcp-option=option:router,$new_ip/" /etc/dnsmasq.conf