我有一种情况,我想要一个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命令行中将参数与文本分离?
答案 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
-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