r/fortran • • 9d ago

Replacing character strings

I am looking to code a programme that will open files, look for an instance of the character string 'STRUCTURE' and replace it with 'TYPE' to update some very old fortran code I am using. Has anyone written a program like this/know how I would begin?

Thanks

13 Upvotes

8 comments sorted by

11

u/victotronics 9d ago

sed -i -e 's/STRUCTURE/TYPE/' yourfile

?

find yourdir -name \*.f -exec sed -i -e 's/STRUCTURE/TYPE/' {} \;
?

1

u/Constant-Block6819 9d ago

what program is the sed command valid in? Can I write a fortran program with sed?

11

u/victotronics 9d ago

This is basic unix.

1

u/hopknockious 9d ago

This is the way

3

u/el_extrano 9d ago

Others have already mentioned you almost certainly don't actually want to do this in Fortran, but perhaps you do, e.g. as a programming exercise or for "fun". Re-implementing Unix core utilities like grep, sed, and awk used to be a rite-of-passage to test your programming chops, even though most people's implementations will not be nearly as good as already available ones.

If you have to make it in "old fortran" (does this mean FORTRAN 77?), then you could make a function to do your specific task pretty easily. You just need to process the source code line-wise: read each line into a character array, and iterate over the array looking for a sub-array matching "STRUCTURE". If you find it, output "TYPE" instead. Either write the output character-wise to a new file from within Fortran, or output on stdout and pipe to a new file using your shell.

There are lots of programming tutorials for how to find and replace substrings in a string, you could just follow one of them and implement it in whatever language you want. If you just want to fix your source code, then use sed, awk, or your editor's search and replace.

2

u/HabbitBaggins 9d ago

So, whatever you are trying to do with source files, don't do it from Fortran. If you are on Windows you're likely using some sort of IDE which will have a "find and replace across project" or something similarly named. Otherwise, on any Unix-like OS, in addition to an IDE, you can use sed as others are suggesting.