Sharky
Sharky

Reputation: 383

Make GNU: get letter/char from variable

I have a variable in a GNU make file :

VAR=DDC

I want to merge these characters into another string and assign them to a different variable, for example:

TOT_VAR=--'D','D','C'--

My first idea was to do something like this pseudocode:

#Pseudo code
TOT_VAR=--'@(letter1, VAR)','@(letter2, VAR)','@(letter3, VAR)'--

But I can't find any function that extracts individual characters. How might I do this?

Upvotes: 1

Views: 116

Answers (2)

Vroomfondel
Vroomfondel

Reputation: 2898

The GNU table toolkit has a function explode which expands a string into a list:

$(call explode,stringlist,string)

Insert a blank after every occurrence of the strings from stringlist in string. This function serves mainly to convert a string into a list:

$(call explode,0 1 2 3 4 5 6 7 8 9,0x1337c0de) --> 0 x1 3 3 7 c0 de

You can access the members of your variable like the following:

include gmtt/gmtt.mk
XPLD_VAR := $(call explode,$([alnum]),$(VAR))
TOT_VAR := --$(word 1,$(XPLD_VAR)),$(word 2,$(XPLD_VAR)),$(word 3,$(XPLD_VAR))--

Upvotes: 0

razlebe
razlebe

Reputation: 7144

You could use sed to do the transformation:

echo DDC | sed -E "s/^(.{1})(.{1})(.{1}).*/--'\1','\2','\3'--/")

What this does:

  1. Pipes the string DDC to sed
  2. Tells sed to parse the string and match the first three characters
  3. Substitute DDC for your replacement format, inserting those three characters into the placeholders \1, \2 and \3

[If you’re on a Linux OS rather than MacOS like me then I think you’ll need to use sed -e rather than sed -E]

As the comment from @Maxim says, you'll need to invoke the shell from make in order to run this command. Building this approach into a simple makefile to illustrate:

VAR=DDC
TOT_VAR:=$(shell echo $(VAR) | sed -E "s/^(.{1})(.{1})(.{1}).*/--'\1','\2','\3'--/")

all:
    echo "$(TOT_VAR)"

Running make all on this yields this output and shows the substitution has worked:

echo "--'D','D','C'--"
--'D','D','C'--

Upvotes: 1

Related Questions