删除bash中最后一次出现的字符串

时间:2020-04-22 08:04:43

标签: bash ubuntu raspberry-pi

有一个名为/etc/rc.local并以exit 0结尾的文件。我需要在文件上附加一些代码,但是exit 0阻止了该代码的执行。

如何使用sedawk和/或tac,仅删除最后一次出现的exit 0,以便可以在脚本的末尾附加更多脚本文件?

脚本运行前的rc.local文件:

if [ -e /boot/disable_rc_setup.txt]; then
  exit 0
fi

if [ -e /boot/setup.txt]; then
  bash /home/pi/setup.sh
  rm /boot/setup.txt
fi

exit 0

脚本运行后当前的rc.local:

if [ -e /boot/disable_rc_setup.txt]; then
  exit 0
fi

if [ -e /boot/setup.txt]; then
  bash /home/pi/setup.sh
  rm /boot/setup.txt
fi

exit 0

curl 192.168.1.5/online
if [ -e /boot/first_boot.txt]; then
  curl 192.168.1.5/first_boot
  rm /boot/first_boot.txt
fi

exit 0

您可以在初始curl命令上方看到exit 0

目标目标rc.local:

if [ -e /boot/disable_rc_setup.txt]; then
  exit 0
fi

if [ -e /boot/setup.txt]; then
  bash /home/pi/setup.sh
  rm /boot/setup.txt
fi

curl 192.168.1.5/online
if [ -e /boot/first_boot.txt]; then
  curl 192.168.1.5/first_boot
  rm /boot/first_boot.txt
fi

exit 0

2 个答案:

答案 0 :(得分:2)

尝试运行:

而不是运行echo "CODE" >> /etc/rc.local
sed -i '/^exit 0/d' /etc/rc.local
echo "CODE" >> /etc/rc.local

仅删除包含exit 0的最后一行代码,因为开头没有尾随空格。如果不确定是否总是这样,请修改代码以确保仅删除最后一次出现的exit 0

答案 1 :(得分:1)

如何使用awk替换字符串exit 0 的最后一次出现。在最后一个rc.local之后,exit 0有了一些多余的代码:

$ cat rc.local
if [ -e /boot/disable_rc_setup.txt]; then
  exit 0
fi

if [ -e /boot/setup.txt]; then
  bash /home/pi/setup.sh
  rm /boot/setup.txt
fi

exit 0

# unwanted code commented out with the above exit

awk:

$ awk '{   
    a[NR]=$0                            # hash records to a index on NR
    if($0~/^ *exit +0 *$/ && NR==FNR)   # remember last exit 0 of the 1st file
        nope=NR
    if(NR==FNR)                         # also remember where the 1st file ended
        last=NR
}
END {
    for(i=1;i<nope;i++)                 # output upto last line before the exit
        print a[i]
    for(i=last+1;i<=NR;i++)             # then output the replacement 
        print a[i]
    for(i=nope;i<=last;i++)             # and from exit to the end of 1st file
        print a[i]
}' rc.local code_to_append

输出:

if [ -e /boot/disable_rc_setup.txt]; then
  exit 0
fi

if [ -e /boot/setup.txt]; then
  bash /home/pi/setup.sh
  rm /boot/setup.txt
fi

curl 192.168.1.5/online
if [ -e /boot/first_boot.txt]; then
  curl 192.168.1.5/first_boot
  rm /boot/first_boot.txt
fi
exit 0

# unwanted code commented out with the above exit