Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use sed to replace a pattern in a file only in lines that contain another pattern

Tags:

regex

sed

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"

like image 438
Matthew Avatar asked Apr 15 '13 17:04

Matthew


People also ask

How do you replace some text pattern with another text pattern in a file?

`sed` command is one of the ways to do replacement task. This command can be used to replace text in a string or a file by using a different pattern.

Can sed replace multiple lines?

Sometimes it requires to replace multiple lines of a file with any particular character or text. Different commands exist in Linux to replace multiple lines of a file. `sed` command is one of them to do this type of task.

How do you match multiple lines in sed?

By using N and D commands, sed can apply regular expressions on multiple lines (that is, multiple lines are stored in the pattern space, and the regular expression works on it): $ cat two-cities-dup2.


1 Answers

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"/'
like image 131
nosid Avatar answered Sep 22 '22 12:09

nosid