title: Sed is not replacing all instances in a file when areas overlap
body: <p>I need to replace several words with other words.</p>
  
  <p>For e.g.: "apple" with "FRUIT" in <code>file</code>, only in these 4 situations:</p>
  
  <ul>
  <li><code>_apple_</code>, has a blank space before and after.</li>
  <li><code>[apple_</code>, has a square opening bracket before and a blank space after.</li>
  <li><code>_apple]</code>, has a blank space before and a square closing bracket after.</li>
  <li><code>[apple]</code>, has square brackets before and after.</li>
  </ul>
  
  <p>I do not want the replaces to occur in any other situation.</p>
  
  <p>I have tried using the following code:</p>
  
  <pre><code>a="apple"
  b="fruit"
  sed -i "s/ $a / $b /g" ./file
  sed -i "s/\[$a /\[$b /g" ./file
  sed -i "s/ $a\]/ $b\]/g" ./file
  sed -i "s/\[$a\]/\[$b\]/g" ./file
  </code></pre>
  
  <p>I thought the option "g" at the end would mean it would replace all instances, but I found this is not a thorough solution. For e.g. if <code>file</code> contains this:</p>
  
  <pre><code>apple spider apple apple spider tree apple tree
  </code></pre>
  
  <p>The third occurrence of "apple" is not being replaced. Also in this, several appearances of the word are not changed:</p>
  
  <pre><code>apple  spider apple apple apple apple apple spider tree apple tree
  </code></pre>
  
  <p>I suspect this is because the shared "space".</p>
  
  <p>How can I get this to find and replace all instances of <code>$a</code> with <code>$b</code>, regardless of any overlap?</p>