Remove item from a Makefile variable?

VariablesMakefileGnu Make

Variables Problem Overview


I have a makefile, which includes several other makefiles, which in turn all add to a variable like this:

VAR := Something SomethingElse
VAR += SomeOtherThing

(...)

Now I wish to remove SomethingElse from the VAR variable. What do I put in place of (...) to do this?

I am using GNU Make, and a GNU Make specific solution will be fine.

Variables Solutions


Solution 1 - Variables

You could use the filter-out text function if you're using GNU Make.

OTHERVAR := $(filter-out SomethingElse,$(VAR))

Solution 2 - Variables

On top of the correct answer above:

VAR = bla1 bla2 bla3 bla4 bla5

TMPVAR := $(VAR)
VAR = $(filter-out bla3, $(TMPVAR))

all:
	@echo "VAR is: $(VAR)"

Output:
VAR is: bla1 bla2 bla4 bla5

Note that this breaks all "recursivity" when filter-out is executed, but that might not matter in your case.

Solution 3 - Variables

As I also have a similar situation, I want to add a new answer. In my case there were also commas into the variable string and, more, I wanted to remove the comma and the last word :

VAR = "bla1, bla2"

In this case filter out is not working (not even in the previous answers, when there are no quotes)

My solution is to use subst :

VAR = "bla1, bla2"

TTT = , bla2
TMPVAR := $(VAR)
SUBST = $(subst $(TTT),, $(TMPVAR))
FILT = $(filter-out $(TTT), $(TMPVAR))

subst:
	@echo "subst : $(SUBST)"

filter:
	@echo "filter-out : $(FILT)"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBjarke Freund-HansenView Question on Stackoverflow
Solution 1 - VariablesMatView Answer on Stackoverflow
Solution 2 - VariablesAndreas Mikael BankView Answer on Stackoverflow
Solution 3 - VariablessopView Answer on Stackoverflow