0

I am trying to find all the Fortran files in a directory and replace some text in that file.

At first i was thinking of using find -regex ... -exec to find all the file extensions for fortran code and make replacements. However, there are a lot of file extensions, is there another way to identify fortran files?

Vasfed
  • 18,013
  • 10
  • 47
  • 53
  • Why are there lots of extensions for fortran files? – Barmar Mar 28 '16 at 20:26
  • 2
    @Barmar Because there are two source forms and capital F denotes the necessity of preprocessing. And because people think that they should distinguish different versions of standard (nonsense like `.f95`,`.f03`), which is silly. Like if we had `.java1` `.java2` ... `.java7`. – Vladimir F Героям слава Mar 28 '16 at 21:12

1 Answers1

2

Here is a very short find command to find all Fortran related files. The most common Fortran files are *.f, *.f90, and their capital letter counterparts. Additionally, .f95, .f03, .f08, and even .for are used. Note that -iregex matches the regular expression case insensitive (in contrast to -regex).

find . -iregex ".*\.F[0-9]*" -o -iregex ".*\.for" 

To do something with this, you can use xargs:

find . -iregex ".*\.F[0-9]*" -o -iregex ".*\.for" | xargs head -1

Replace head -1 with whatever you want to do with the files.


Another way to work with that is using a loop such as:

for file in $(find . -iregex ".*\.F[0-9]*" -o -iregex ".*\.for"); do
  head -1 "$file"
done

This gives you a bit more flexibility than the xargs approach, and is easier to read.

Alexander Vogt
  • 17,879
  • 13
  • 52
  • 68
  • Unless output is very simple (no whitespace, no special character) or you explicitly want word-splitting you generally shouldn't use `for ... in $(command)` in bash. See http://stackoverflow.com/a/7039579/3076724 for some alternatives (missing `IFS=` in a few places) – Reinstate Monica Please Mar 28 '16 at 23:21