Bash

bash - sed: -e 表達式 #1, char 15: 未終止的 `s’ 命令

  • May 18, 2020

我嘗試sed在循環中使用命令來替換 IP 地址,但它總是給我這個錯誤:

sed: -e expression #1, char 15: unterminateds’命令`

即使它沒有失去結束斜線。

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

這裡會出現什麼問題以及如何解決?

$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.

引用自:https://unix.stackexchange.com/questions/250763