我尝试sed
在循环内使用命令来替换 IP 地址,但它总是给我这个错误:
sed: -e expression #1, char 15: unterminated
s'命令`
即使它没有缺少结束斜杠。
IP 地址的格式示例:26.236.16.233
这是我的代码:
readarray thearray < /root/scripts/ipaddr.info
Filepath=/var/named/chroot/var/named/$Serverdmn
for item in ${!thearray[@]}; do
echo -e "IP: ${thearray[$item]}."
echo -e "Change this IP? (y/n)"
read Useranswer
if [ $Useranswer = y ]; then
echo -e "Please type the IP address:"
read Firstipaddress
oldipaddr=${thearray[$item]}
new_oldipaddr=${oldipaddr%.*}.0
newipaddr=$Firstipaddress
new_ipaddr=${newipaddr%.*}.0
# do the change on all files
sed -i "s/$oldipaddr/$Firstipaddress/g" /root/scripts/ipaddr.info
sed -i "s/$oldipaddr/$Firstipaddress/g" /etc/application/config
sed -i "s/$oldipaddr/$Firstipaddress/g" $Filepath
sed -i "s/$new_oldipaddr/$new_ipaddr/g" $Filepath
elif [ $Useranswer = n ]; then
:
fi
done
这里会出现什么问题以及如何解决?
答案1
您的$oldipaddr
(从 获得的${thearray[$item]}
)值包含从 读取的换行符/root/scripts/ipaddr.info
,这导致sed
命令跨行分割,例如
Please type the IP address:
1.2.3.4
sed -i s/26.236.16.233
/1.2.3.4/g /root/scripts/ipaddr.info
尝试
readarray -t thearray < ipaddr.info
从help mapfile
-t Remove a trailing newline from each line read.