简体   繁体   中英

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

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.

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM