title: Matching words that are not inside any comment with regular expressions and Unix tools
body: <p>How can I use sed, awk or something else to match for the occurences of the word <code>type</code>, where the lines containing <code>type</code> do not have any occurences of <code>!</code> before the occurence of <code>type</code>? Then replace <code>type</code> with something else?</p>
  
  <p>So I am asking to match the occurences of word <code>type</code> which aren't inside Fortran 90 comments.</p>
  
  <p><strong>EDIT</strong></p>
  
  <ul>
  <li>Multiple occurences of the word on the same line, before <code>!</code> should also be replaced. </li>
  <li><code>!</code> does not function as comment character when inside single or double quotes, so occurences following <code>"!"</code>, <code>'!'</code>, <code>"'!'"</code> should also be replaced. I think this makes the task quite complicated.</li>
  <li>Words that contain <code>type</code> should not be changed, like <code>footype</code>.</li>
  </ul>
  
  <p>Possible solution:</p>
  
  <pre><code>awk -F '!' -v OFS='!' '{ gsub("\\&lt;type\\&gt;", "replacement", $1) } 1' file
  </code></pre>
  
  <p>seems to solve the issue, but it still cannot handle the <code>!</code> inside quotes.</p>
  
  <p><strong>Minimal example</strong></p>
  
  <pre><code>  type = 2 +type
    type type 
    lel = "!" type
    lel = '!' type
    lel = "'!'" type
    ! type=2
  type
  footype
  </code></pre>
  
  <p>Should turn into:</p>
  
  <pre><code>  replacement = 2 +replacement
    replacement replacement 
    lel = "!" replacement
    lel = '!' replacement
    lel = "'!'" replacement
    ! type=2
  replacement
  footype
  </code></pre>