title: How to use sed to replace a pattern in a file only in lines that contain another pattern
body: <p>In my specific situation, I need to loop through several hundred files that contain a variable which stores a URL. All of the URLs are different, but for the sake of this example we can assume they all end with 'com"'</p>
  
  <p>I need to add some text immediately following the com</p>
  
  <p>Because all of the URLs will have different domains I cannot use a sed command like: </p>
  
  <pre><code>sed -i 's/^ENVIRONMENT="someurl.com"/ENVIRONMENT="someurl.com.origin.net"/g'
  </code></pre>
  
  <p>Because the files contain other lines which may contain com, I cannot use something like:</p>
  
  <pre><code>sed -i 's/com/com.origin.net/g'
  </code></pre>
  
  <p>I need to do this search and replace only on a specific line containing a pattern, such as from my example below in regex:</p>
  
  <pre><code>^ENVIRONMENT.*
  </code></pre>
  
  <p>If I could focus the use of sed only to the line that matched the above pattern then I could use some adaptation of sed such as <code>sed -i 's/com/com.origin.net/g'</code>.  I could of course write an overly complicated bash script to do this, but I know there is a nice one liner way to tell sed to find a pattern, only work on the line that the pattern is found in, and search and replace another pattern with a new string.</p>
  
  <p>In searching Google, the only semi relevant link I found about this was: <a href="https://unix.stackexchange.com/questions/37518/how-to-sed-only-that-lines-that-contains-given-string">How to sed only that lines that contains given string?</a>. But it didn't sufficiently answer my question. Also being able to constrain sed in general to just a line that matches a pattern would by a nice tool to add to me sed arsenal.</p>
  
  <p>Any help that leads to solution here will be very appreciated.</p>
  
  <p>Here is an example of a file</p>
  
  <pre><code>### Example File
  #
  #
  # someurl.com
  
  ENVIRONMENT="someurl.com"
  
  </code></pre>
  
  <p>I want to replace <code>ENVIRONMENT="someurl.com"</code> with <code>ENVIRONMENT="someurl.com.orign.net"</code></p>