桑达:如何找到替换字符串中特定模式是位于一个文件后, [英] Sed: How to replace a string found after a specific pattern is located in a file

查看:86
本文介绍了桑达:如何找到替换字符串中特定模式是位于一个文件后,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个文件中的以下列表:

 整数参数:: NI = 1024
整数参数:: NJ = 256
整数参数:: NK = 16

和希望基于字符串'NI ='像'512',例如一个新的字符串进行搜索,然后更换后面的字符串(在这种情况下,'1024')(我想preserve空间)。如何使用SED这个?请注意,我想基本上只是擦任何东西在等号后到来,这是因为有时串不会是一个简单的整数,这可能是这样的'1.D0。并且在某些情况下,有可能会提前注释。所以,我只是想消灭无论是在等号的前面,并用新值替换。

其结果将是:

 整数参数:: NI = 512
整数参数:: NJ = 256
整数参数:: NK = 16


解决方案

GNU sed的支持扩展定期EX pressions如果你给它的 -r 标记。

  SED -re的/(:: NI =)[^ =] * $ / \\ 1 512 /'文件

更重要的是,比赛为多个空格。

  SED -re的/(:: \\ S +妮\\ s + =)[^ =] * $ / \\ 1 512 /'文件

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

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.

The result would be:

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

解决方案

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

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

Better yet, match for multiple whitespace.

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

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

这篇关于桑达:如何找到替换字符串中特定模式是位于一个文件后,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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