Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
493 views
in Technique[技术] by (71.8m points)

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

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"

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 , 1, etc.

sed -e '/^(ENVIRONMENT="[^"]*.com)"/ s//1.origin.net"/'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...