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
`sed` command is one of the ways to do replacement task. This command can be used to replace text in a string or a file by using a different pattern.
Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input. txt. The s is the substitute command of sed for find and replace.
The sed command can add a new line after a pattern match is found. The "a" command to sed tells it to add a new line after a match is found. The sed command can add a new line before a pattern match is found. The "i" command to sed tells it to add a new line before a match is found.
How SED Works. In the syntax, you only need to provide a suitable “new string” name that you want to be placed with the “old string”. Of course, the old string name needs to be entered as well. Then, provide the file name in the place of “file_name” from where the old string will be found and replaced.
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.
If I understand you correctly, something like this should do it:
sed 's/\(ni = \).*/\1REPLACEMENT/'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With