Makefile:返回字符串的前两个字符

发布于 2024-11-29 22:10:58 字数 209 浏览 0 评论 0原文

给定 Makefile 中的字符串,是否可以使用 Makefile 语法(不使用 shell 调用)提取未知字符串的前两个字符?

例如,

VAR := UnKnown
VAR_TERSE = $(call get_first_two_chars, $(VAR))

define get_first_two_char
...
endef

Given a string in a Makefile, is it possible to extract the first two characters of an unknown string using Makefile syntax (without using shell calls)?

for instance,

VAR := UnKnown
VAR_TERSE = $(call get_first_two_chars, $(VAR))

define get_first_two_char
...
endef

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

冰火雁神 2024-12-06 22:10:58

嗯,这是可以做到的,但是手工实现起来相当混乱。最简单的方法是获取 GNU Make 标准库,它有一个内置的 substr< /代码> 函数。如果这太过分了,您可以从库中提取该函数,但正如我所说,它非常混乱。

本质上,您对字符串进行一系列替换,以在每个字符后插入一个空格:

EMPTY:=
SPACE:=$(EMPTY) $(EMPTY)
VAR := UnKnown
TMP:=$(subst a,a ,$(subst b,b ,$(subst c,c ,.........$(VAR)))))
# TMP now has "U n K n o w n"

接下来,您可以使用 $(wordlist) 函数来获取中间结果的前两个“单词”:

TMP2:=$(wordlist 1,2,$(TMP))
# TMP2 now has "U n"

最后,您再次使用 $(subst) ,现在删除您最初注入的空格:

VAR_TERSE := $(subst $(SPACE),,$(TMP2))
# VAR_TERSE now has "Un"

Well, it can be done, but it's pretty messy to implement by hand. The easiest thing to do is to get the GNU Make Standard Library, which has a built-in substr function. If that's overkill, you can extract just that function from the library, but like I said, it's surprisingly messy.

Essentially you do a series of substitutions on the string to insert a space after each character:

EMPTY:=
SPACE:=$(EMPTY) $(EMPTY)
VAR := UnKnown
TMP:=$(subst a,a ,$(subst b,b ,$(subst c,c ,.........$(VAR)))))
# TMP now has "U n K n o w n"

Next you can use the $(wordlist) function to grab the first two "words" of the intermediate result:

TMP2:=$(wordlist 1,2,$(TMP))
# TMP2 now has "U n"

Finally, you use $(subst) again, now to strip out the space that you injected originally:

VAR_TERSE := $(subst $(SPACE),,$(TMP2))
# VAR_TERSE now has "Un"
苍风燃霜 2024-12-06 22:10:58

我真的不赞成强迫Make做它显然不想做的事情,但是……我无法抗拒一个好的谜题。

$(eval FOO := $$(VAR))
$(eval FOO := $$(FOO))
VAR_TERSE:= $(VAR:$(FOO)=)

I really don't approve of forcing Make to do things it clearly doesn't want to do, but... I can't resist a good puzzle.

$(eval FOO := $$(VAR))
$(eval FOO := $$(FOO))
VAR_TERSE:= $(VAR:$(FOO)=)
再浓的妆也掩不了殇 2024-12-06 22:10:58

使用 shell 和 sed 吗?

define get_first_two_char
$(shell echo $1 | sed 's/^\(..\).*/\1/' )
endef

Use the shell and sed?

define get_first_two_char
$(shell echo $1 | sed 's/^\(..\).*/\1/' )
endef
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文