0

I went through some posts, but still didn't get how it work.

My request is:

for i in *.json
do
  file = `echo $i |cut -d _ -f2`
  echo ${file}
  # do the rest tasks
done

How to convert above script to target of Makefile?

Here is what I tried

foo: 
    for i in *.json; do      \
       $(eval FILE = $(shell echo $$i |cut -d _ -f2));    \
       echo $(FILE) ;\
    done

But it doesn't work

Bill
  • 2,494
  • 5
  • 26
  • 61

1 Answers1

1

Using $(eval) or $(shell) is ... not even wrong.

foo: 
    for i in *.json; do \
       file=$$(echo "$$i" |cut -d _ -f2); \
       echo "$$file"; \
    done

Notice the quoting of the filename variables, and the absence of spaces around the = assignment operator, and the doubling of any dollar sign in order to pass it through from make to the shell.

However, the shell provides a much better mechanism for this;

foo:
    for i in *.json; do \
        j=$${i#*_}; \
        echo "$${j%%_*}"; \
    done

or perhaps

foo:
    printf '%s\n' *.json \
    | sed 's/[^_]*_\([^_]*\)_.*/\1/'

If you only expect a single underscore, both of these can be further simplified.

Or maybe you are just looking for

makefile_variable := $(foreach x,$(wildcard *.json),$(word 2,$(subst _, ,$x)))
tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Thanks a lot. Why the output is different: `$${file}` and `$(file)`? – Bill Jan 13 '20 at 08:48
  • and how to use `makefile_variable` in target? – Bill Jan 13 '20 at 08:50
  • 1
    As already explained, a double dollar sign gets passed through to the shell, whereas a single dollar sign gets evaluated by `make` itself. To get `make` to interpolate the variable, simply reference it like any variable: `$(makefile_variable)`. If you need help, ask a new question (but please search and/or read some documentation first). – tripleee Jan 13 '20 at 08:56