Hugolpz
Hugolpz

Reputation: 18258

Make: how to replace character within a make variable?

I have a variable such :

export ITEM={countryname}

this can be :

   "Albania", 
   "United States"   // with space
   "Fs. Artic Land"  // dot
   "Korea (Rep. Of)" // braket
   "Cote d'Ivoir"    // '

This variable $(ITEM) is passed to other commands, some needing is as it (fine, I will use $(ITEM)), some MUST HAVE characters replacements, by example, to go with mkdir -p ../folder/{countryname} :

   "Albania"          // => Albania
   "United States"    // => United_States
   "Fs. Artic Land"   // => Fs\._Artic_Land
   "Korea (Rep. Of)"  // => Korea_\(Rep\._Of\)
   "Cote d'Ivoire"    // => Cote_d\'Ivoire 

So I need a new make variable such

export ITEM={countryname}
export escaped_ITEM=$(ITEM).processed_to_be_fine

How should I do this characters replacements within my makefile ? (to keep things simple and not have to do an external script). I was thinking to use some transclude tr or something.

Note: working on Ubuntu.

Upvotes: 3

Views: 9154

Answers (2)

tripleee
tripleee

Reputation: 189447

You can use the subst function in GNU Make to perform substitutions.

escaped_ITEM := $(subst $e ,_,$(ITEM))

(where $e is an undefined or empty variable; thanks to @EtanReisner for pointing it out).

You will need one subst for each separate substitution, though.

If at all possible, I would advise against this, however -- use single, machine-readable tokens for file names, and map them to human readable only as the very last step. That's also much easier in your makefile:

human_readable_us=United States
human_readable_kr=Korea (Rep. of)
human_readable_ci=Côte d'Ivoire
human_readable_tf=FS. Antarctic Lands

stuff:
        echo "$(human_readable_$(ITEM))"

Upvotes: 6

Etan Reisner
Etan Reisner

Reputation: 80931

Given the input simply "quoting" the country "names" when using them in the shell will work fine (for the few shown here) but double quoting arbitrary strings is not safe as any number of things can still evaluate inside double quotes (and with the way make operates even double quotes themselves in the string will cause problems).

If you need to pass "random" strings to the shell their is only one safe way to do that: replace every instance of ' (a single quote) in the string with '\'' and then wrap the string in ' (single quotes). (Depending on the consumer of the string replacing each ' with \047 can also work.)

Upvotes: 2

Related Questions