7

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

3 Answers 3

11

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.

1
  • What if its ni:1024? without a space
    – alper
    Jun 13, 2020 at 11:22
6

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

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

1
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 ni somewhere in another string.

2
  • it's better to write sed -e 's/:: ni = [0-9]+$/:: ni = 512/' Jan 11, 2017 at 9:00
  • @AntonAstafiev: that depends on how widely you want the code to work. Some variants of sed support + without further switches; many do not and POSIX doesn't require them to do so. You could use [0-9]\{1,\} to do it, but what I wrote is more easily understood. Jan 11, 2017 at 14:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.