gmake中的链接字符串替换

时间:2019-01-11 14:55:46

标签: gnu-make

在GNU make中,我想对包含多个“占位符”的文本块执行多个字符串替换,例如:

MYTEXT:= blabla _FIRST_PLACEHOLDER_ blabla _SECOND_PLACEHOLDER_whateverblabla_THIRD_PLACEHOLDER_blablabla

所以我想用以下值替换“占位符”:

_FIRST_PLACEHOLDER_ => FIRST_VAL
_SECOND_PLACEHOLDER_ => SECOND_VAL
_THIRD_PLACEHOLDER_ => THIRD_VAL
...

下面显示了一种获取我想要的结果的可怕方法:

$(subst _FIRST_PLACEHOLDER_,FIRST_VAL, $(subst _SECOND_PLACEHOLDER_,SECOND_VAL, $(subst _THIRD_PLACEHOLDER_,THIRD_VAL, $(MYTEXT))))

一个解决方案将很容易在make领域之外找到,但是有没有一种比上述更好的方法来执行这种递归替换,同时又保持在make范围之内?我尝试使用$(foreach),但这只是将每次替换应用到初始$(MYTEXT)的结果串联起来。

1 个答案:

答案 0 :(得分:0)

迭代解决方案

此解决方案需要覆盖变量_p_x

# -*- gnu-make -*-
ORIGINAL         := 123__PLACE_HOLDER__1567__PLACE_HOLDER__2890
REPLACEMENT_LIST :=       \
    __PLACE_HOLDER__1=ABC \
    __PLACE_HOLDER__2=DEF \

_replace1 = $(eval _x := $(subst $(word 1,$(1)),$(word 2,$(1)),$(_x)))
replace   = $(strip \
    $(eval _x := $(strip $(2))) \
    $(foreach _p,$(strip $(1)),$(call _replace1,$(subst =, ,$(_p)))) \
    $(_x) \
    $(eval _x :=) \
)

$(info ORIGINAL:    '$(ORIGINAL)')
$(info REPLACEMENT: '$(call replace,$(REPLACEMENT_LIST),$(ORIGINAL))')

.PHONY: all
all:

示例运行:

$ make 
ORIGINAL:    '123__PLACE_HOLDER__1567__PLACE_HOLDER__2890'
REPLACEMENT: '123ABC567DEF890'
make: Nothing to be done for 'all'.

递归解决方案

此解决方案的优点是不修改任何变量。

_replace2 = $(subst $(word 1,$(1)),$(word 2,$(1)),$(2))
_replace1 = $(call replace,$(2),$(call _replace2,$(subst =, ,$(1)),$(3)))
replace   = $(if $(1),$(call _replace1,$(firstword $(1)),$(wordlist 2,1000000,$(1)),$(2)),$(2))

_replace1 = $(subst $(word 1,$(1)),$(word 2,$(1)),$(2))
replace   = $(if $(1),$(call replace,$(wordlist 2,1000000,$(1)),$(call _replace1,$(subst =, ,$(firstword $(1))),$(2))),$(2))