Search code examples
bashmakefilefortranfortran90

grep and sed in a Fortran Makefile


I have a Fortran code that can be compiled by the following Makefile:

FC = mpif90  
FFLAGS := ...

TARGET = run1

SRC = main.f90 param.f90 ...
OBJ = $(SRC:.f90=.o)

all: $(TARGET)
$(TARGET): $(OBJ) $(FC) $(FFLAGS)
...

In the above, the TARGET can be run1 or run2 or run3, depending on the value of a variable in my script. For example, if I have the following in param.f90:

character(len=1), parameter :: case_num = "1"

Then, I want the TARGET variable to be set as run1. Now, the question is how to do that automatically without manually changing the Makefile every time?

I have tried something like

num = $(grep 'case_num = "' param.f90 | sed -n -e 's/^.*case_num = "//p' | cut -c1-1)
TARGET = run$num

in the Makefile, which doesn't work. I have checked that the grep and sed sentence is correct in a regular bash script. How to do this in a Fortran Makefile? Any help is appreciated.


Solution

  • Your makefile appears to a GNU Make makefile. To assign the output of a shell command to a make variable, you need to use the $(shell ...) function, like:

    num := $(shell grep 'case_num = "' param.f90 | sed -n -e 's/^.*case_num = "//p' | cut -c1-1)
    TARGET := run$(num)