title: Remove last occurrence of string in bash
body: <p>There's a file called <code>/etc/rc.local</code> that ends with <code>exit 0</code>. I need to append some code onto the file, but the <code>exit 0</code> is preventing that code from executing.</p>
  
  <p>Using <code>sed</code>, <code>awk</code> and/or <code>tac</code>, how can I remove only the last occurrence of <code>exit 0</code> so that more script can be appended onto the end of the file?</p>
  
  <p>rc.local file before my script runs:</p>
  
  <pre><code>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
  
  </code></pre>
  
  <p>Current rc.local after script runs:</p>
  
  <pre><code>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
  
  </code></pre>
  
  <p>You can see the <code>exit 0</code> above the initial curl command.</p>
  
  <p>Desired Goal rc.local:</p>
  
  <pre><code>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
  
  </code></pre>