title: Reverse file using tac and sed
body: <p>I have a usecase where I need to search and replace the last occurrence of a string in a file and write the changes back to the file. The case below is a simplified version of that usecase:</p>
  
  <p>I'm attempting to reverse the file, make some changes reverse it back again and write to the file. I've tried the following snippet for this:</p>
  
  <pre><code>tac test | sed s/a/b/ | sed -i '1!G;h;$!d' test
  </code></pre>
  
  <p>test is a text file with contents:</p>
  
  <pre><code>a
  1 
  2 
  3
  4
  5
  </code></pre>
  
  <p>I was expecting this command to make no changes to the order of the file, but it has actually reversed the contents to:</p>
  
  <pre><code>5
  4
  3
  2
  1
  b
  </code></pre>
  
  <p>How can i make the substitution as well as retain the order of the file?</p>