如何使用 sed 仅在包含另一个模式的行中替换文件中的模式 [英] How to use sed to replace a pattern in a file only in lines that contain another pattern

查看:24
本文介绍了如何使用 sed 仅在包含另一个模式的行中替换文件中的模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的特定情况下,我需要遍历包含存储 URL 的变量的数百个文件.所有的 URL 都不同,但为了这个例子,我们可以假设它们都以 '​​com"' 结尾

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

我需要在 com 之后立即添加一些文本

I need to add some text immediately following the com

因为所有的 URL 都有不同的域,所以我不能使用像这样的 sed 命令:

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'

因为文件包含其他可能包含 com 的行,我不能使用类似的东西:

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.*

如果我只能将 sed 的使用集中在与上述模式匹配的行上,那么我可以使用 sed 的一些改编版本,例如 sed -i 's/com/com.origin.net/g'.我当然可以编写一个过于复杂的 bash 脚本来执行此操作,但我知道有一种很好的单行方式告诉 sed 查找模式,仅在找到该模式的行上工作,然后搜索并替换另一个模式使用新字符串.

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.

在搜索谷歌时,我找到的唯一半相关链接是:如何仅 sed 包含给定字符串的行?.但它并没有充分回答我的问题.还能够将 sed 通常限制为与模式匹配的行,这将是一个很好的工具,可以添加到我的 sed 武器库中.

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.

这是一个文件的例子

### Example File
#
#
# someurl.com

ENVIRONMENT="someurl.com"

我想将 ENVIRONMENT="someurl.com" 替换为 ENVIRONMENT="someurl.com.orign.net"

推荐答案

以下命令行显示了两种可能的解决方案: 您可以使用 /regex/ 将替换限制为某些行.您可以使用匹配的文本替换 1

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

这篇关于如何使用 sed 仅在包含另一个模式的行中替换文件中的模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆