Linux Sed:如何替换在特定模式位于文件中后找到的字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19737398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:15:13  来源:igfitidea点击:

Sed: How to replace a string found after a specific pattern is located in a file

regexlinuxbashunixsed

提问by Isopycnal Oscillation

If I have the following list in a file:

如果我在文件中有以下列表:

integer, parameter :: ni = 1024
integer, parameter :: nj = 256
integer, parameter :: nk = 16

and want to search based on the string 'ni =', and then replace the string that follows (in this case '1024') with a new string like '512' for example (I would like to preserve the space). How can I use sed for this? Note that I would like to just essentially wipe anything that comes after the equal sign, this is because sometimes the string will not be a simple integer, it might be something like '1.D0'. And in some cases there may be comments ahead. So I just want to wipe out whatever is in front of the equal sign and replace with the new value.

并且想要根据字符串“ni =”进行搜索,然后将后面的字符串(在本例中为“1024”)替换为一个新字符串,例如“512”(我想保留空格)。我该如何使用 sed 呢?请注意,我只想擦除等号后面的任何内容,这是因为有时字符串不是简单的整数,它可能类似于“1.D0”。在某些情况下,可能会提前发表评论。所以我只想清除等号前面的任何内容并替换为新值。

The result would be:

结果将是:

integer, parameter :: ni = 512
integer, parameter :: nj = 256
integer, parameter :: nk = 16

采纳答案by hwnd

GNU sed supports extended regular expressions if you give it the -rflag.

如果你给它这个-r标志,GNU sed 支持扩展的正则表达式。

sed -re 's/(:: ni =)[^=]*$/ 512/' file

Better yet, match for multiple whitespace.

更好的是,匹配多个空格。

sed -re 's/(::\s+ni\s+=)[^=]*$/ 512/' file

The \1is a reference to what's matched in parentheses ( ), so we replace with \1and a new value.

\1是什么括号匹配的参考( ),所以我们将其替换\1和新的价值。

回答by Jonathan Leffler

sed -e 's/:: ni = [0-9][0-9]*$/:: ni = 512/'

This looks for plausible context around the match specified to minimize the chance of finding nisomewhere in another string.

这会在指定的匹配项周围寻找合理的上下文,以最大限度地减少ni在另一个字符串中找到某处的机会。

回答by user2719058

If I understand you correctly, something like this should do it:

如果我理解正确的话,应该这样做:

sed 's/\(ni = \).*/\1REPLACEMENT/'

sed 's/\(ni = \).*/\1REPLACEMENT/'