0

I'm stuck in finding a way to modify multiple lines in multiple files that contain specific words/characters but not others. To be more specific, a would like to transform all variable declarations in fortran files from real to real(kind=r8). For example the lines below:

  • var= (var1*REAL(j)-var2*REAL(j)*var3)
  • REAL :: pwr10
  • INTRINSIC REAL
  • REAL(kind=r16) :: qr(n), qaorg, qx
  • REAL, DIMENSION(-1:nx, -1:ny) :: arg1
  • REAL(kind=r8) :: y3

should become:

  • var= (var1*REAL(j)-var2*REAL(j)*var3)

  • REAL(kind=r8) :: pwr10

  • INTRINSIC REAL
  • REAL(kind=r16) :: qr(n), qaorg, qx
  • REAL(kind=r8), DIMENSION(-1:nx, -1:ny) :: arg1
  • REAL(kind=r8) :: y3

I know how to select the specific lines using grep but not using sed to modify them. can someone help please?

2
$ sed 's/REAL\([^(].*::\)/REAL(kind=r8)\1/' file
var= (var1*REAL(j)-var2*REAL(j)*var3)
REAL(kind=r8) :: pwr10
INTRINSIC REAL
REAL(kind=r16) :: qr(n), qaorg, qx
REAL(kind=r8), DIMENSION(-1:nx, -1:ny) :: arg1
REAL(kind=r8) :: y3

The sed expression

s/REAL\([^(].*::\)/REAL(kind=r8)\1/

will substitute all REAL with REAL(kind=r8) provided that

  1. The string REAL is not immediately followed by a (.
  2. There is a :: somewhere later on the same line.

The way I've written it, the REAL string may otherwise occur anywhere on the line. Use ^REAL in place of the first REAL in the expression if the word has occur first on the line (with no spaces or anything between the beginning of the line and the word).

0
perl  -pe '/\h::\h/ && /^\h*REAL(?!\()\K/ and s//(kind=r8)/' input.txt

to be read as:

  • when each line has a whitespace delimited "::" substring.
  • the keyword "REAL" begins at beginning of line optionally preceded by whitespace and does not see an opening bracket to it's right.
  • when both the above conditions are met, we perform the substitution.
  • the s//(kind=r8)/ command means use the regex from the previous successful match and replace that with whatever's in the RHS.

Output

var= (var1*REAL(j)-var2*REAL(j)*var3)
REAL(kind=r8) :: pwr10
INTRINSIC REAL
REAL(kind=r16) :: qr(n), qaorg, qx
REAL(kind=r8), DIMENSION(-1:nx, -1:ny) :: arg1
REAL(kind=r8) :: y3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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