如何在make中分割字符串?

39

我需要在我的Makefile中传入一个参数,该参数由一个形如主机标识符的字符串组成

host[:port]

冒号和端口号是可选的,因此以下所有格式都是有效的:

foo.example.com
ssl.example.com:443
localhost:5000

我想把字符串按可选冒号分隔并将值赋给变量,以便 HOST 包含 foo.example.comssl.example.comlocalhost 等等,以及 PORT 包含默认端口80、443和500。

1个回答

61
# Retrieves a host part of the given string (without port).
# Param:
#   1. String to parse in form 'host[:port]'.
host = $(firstword $(subst :, ,$1))

# Returns a port (if any).
# If there is no port part in the string, returns the second argument
# (if specified).
# Param:
#   1. String to parse in form 'host[:port]'.
#   2. (optional) Fallback value.
port = $(or $(word 2,$(subst :, ,$1)),$(value 2))

使用方法:

$(call host,foo.example.com) # foo.example.com
$(call port,foo.example.com,80) # 80

$(call host,ssl.example.com:443) # ssl.example.com
$(call port,ssl.example.com:443,80) # 443

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接