Danijel
Danijel

Reputation: 8610

GNU make `foreach`: get rid of comma in the last list member?

I am using a foreach to generate a list in a GNU makefile:

DEFINES += DEF1
DEFINES += DEF2
...
MY_DEFINES := $(foreach define,$(DEFINES),\"$(define)\",\n)

When I print the defines into a file

echo -e "$(MY_DEFINES)";

I get the following:

DEF1,
DEF2,

How do I get rid of a comma in the last list member?
My output needs to be:

DEF1,
DEF2

Upvotes: 0

Views: 195

Answers (2)

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136425

One way it to use head to cut off the last 2 bytes, e.g.:

echo -e "$(MY_DEFINES)" | head --bytes=-2

Another way is to prefix each element with ,\n apart from the first element:

MY_DEFINES := $(firstword ${DEFINES})$(foreach define,$(wordlist 2,$(words ${DEFINES}),${DEFINES}),\n,\"$(define)\")

Upvotes: 2

Renaud Pacalet
Renaud Pacalet

Reputation: 29260

A step-by-step solution could be:

COMA    := ,
DEFINES += DEF1
DEFINES += DEF2
...
MY_DEFINES := $(patsubst %,%$(COMA),$(DEFINES))FOOBAR
MY_DEFINES := $(patsubst %$(COMA)FOOBAR,%,$(MY_DEFINES))
MY_DEFINES := $(patsubst %,%\n,$(MY_DEFINES))

Where FOOBAR is any string that you are 100% sure will never be part of one of your DEFINES.

Upvotes: 0

Related Questions