8

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"'

I need to add some text immediately following the com

Because all of the URLs will have different domains I cannot use a sed command like:

sed -i 's/^ENVIRONMENT="someurl.com"/ENVIRONMENT="someurl.com.origin.net"/g'

Because the files contain other lines which may contain com, I cannot use something like:

sed -i 's/com/com.origin.net/g'

I need to do this search and replace only on a specific line containing a pattern, such as from my example below in regex:

^ENVIRONMENT.*

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 sed -i 's/com/com.origin.net/g'. 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.

In searching Google, the only semi relevant link I found about this was: How to sed only that lines that contains given string?. 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.

Any help that leads to solution here will be very appreciated.

Here is an example of a file

### Example File
#
#
# someurl.com

ENVIRONMENT="someurl.com"

I want to replace ENVIRONMENT="someurl.com" with ENVIRONMENT="someurl.com.orign.net"

0

1 Answer 1

12

The following command line shows two possible solutions: You can restrict the replacement to certain lines with /regex/. And you can use the matched text in replacements with \0, \1, etc.

sed -e '/^\(ENVIRONMENT="[^"]*\.com\)"/ s//\1.origin.net"/'
4
  • Thanks this is exactly what I wanted to accomplish. Especially being able to insert the matched text. Just to clarify my understanding of the matched text replacement aspect of the answer you provided; what could I accomplish with the \0? Also, if I use a \2 for example, would this insert say a second matched text from regex. For example if I was searching for a line with 2 patterns to match on.
    – Matthew
    Apr 16, 2013 at 17:09
  • 1
    Take a look into the GNU sed manual: backreferences in regular expressions
    – nosid
    Apr 16, 2013 at 17:57
  • You're using what sed calls addresses?
    – Geremia
    Mar 4, 2017 at 18:11
  • What about all lines not matching a regexp? How would that be done? thanks
    – Geremia
    Mar 4, 2017 at 18:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.