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

24,984

Solution 1

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.

Solution 2

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

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

Solution 3

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.

Share:
24,984
Isopycnal Oscillation
Author by

Isopycnal Oscillation

Updated on July 09, 2022

Comments

  • Isopycnal Oscillation
    Isopycnal Oscillation almost 2 years

    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