Search code examples
makefilewildcardgnu-makegnu

How to replace using patsubst Makefile?


I have a makefile somewhat like this. I need to generate a file and move that as abc.cpp (Basically get rid of anything after underscore including underscore

xyz:= abc_def

$(xyz):
       (some commands here which generates a file)

       mv file /tmp/$(patsubst _%,"",$@) 
       
       However this does not work. In fact it doesn't ever match the underscore "_" in $@
       
       mv file /tmp/abc.cpp is what i want

How does the "%" wildcard work in patsusbst?


Solution

  • The patsubst function won't work for you, because it can match only ONE pattern. You want to match two patterns: anything before the _ and anything after the _. $(patsubst _%,...) only matches words that begin with _, and your word abc_def doesn't begin with _, so the patsubst is a no-op.

    To do what you want using GNU make functions you need to play a trick; something like:

    mv file /tmp/$(firstword $(subst _, ,$@))
    

    This splits the string into words by changing the _ to space, then takes the first word.