shell 在Makefile中拆分和剪切字符串

5anewei6  于 2022-11-30  发布在  Shell
关注(0)|答案(3)|浏览(504)

我正在编写Makefile。

version := v39.0.12.8    // format rules: va.b.c.d

我想得到基于格式的“version_a”,在本例中是“39”。如何做到这一点?也许通过“sed/cut/awk,但我不熟悉这些shell命令。
例如:

version         version_a  version_b   version_c  version_d
v39.0.12.8      39         0            12        8
v87.2.9.17      87         2            9         17
v142.98.77.68   142        98           77        68
n53p2ov0

n53p2ov01#

这可以通过make函数来实现,如下所示:

$ cat Makefile
version := v39.0.12.8

version_tuple := $(subst ., ,$(version:v%=%))

version_a := $(word 1,$(version_tuple))
version_b := $(word 2,$(version_tuple))
version_c := $(word 3,$(version_tuple))
version_d := $(word 4,$(version_tuple))

all:
        echo version_tuple = $(version_tuple)
        echo version_a = $(version_a)
        echo version_b = $(version_b)
        echo version_c = $(version_c)
        echo version_d = $(version_d)

输出量:

$ make -s
version_tuple = 39 0 12 8
version_a = 39
version_b = 0
version_c = 12
version_d = 8
nnsrf1az

nnsrf1az2#

使用gmtt,可以对版本号执行glob匹配:

include gmtt/gmtt.mk

version := v39.0.12.8

matchresult := $(call glob-match,$(version),v*.*.*.*)

$(info [$(matchresult)])

major := $(word 2,$(matchresult))
minor := $(word 4,$(matchresult))
bugfix := $(word 6,$(matchresult))
buildcnt := $(word 8,$(matchresult))

$(info Major = $(major))
$(info Minor = $(minor))
$(info Bugfix = $(bugfix))
$(info Buildcnt = $(buildcnt))

$(if $(call int-ge,$(major),39),$(info Major is 39 or higher!))
zdwk9cvp

zdwk9cvp3#

  • 作为其他优秀答案的替代方案,以下是我的首选解决方案。*

生成文件:

split-dot = $(word $2,$(subst ., ,$1))

version := v39.0.12.8
version_a := $(call split-dot,$(version:v%=%),1)
version_b := $(call split-dot,$(version),2)
version_c := $(call split-dot,$(version),3)
version_d := $(call split-dot,$(version),4)

all:
    $(info version_a=$(version_a))
    $(info version_b=$(version_b))
    $(info version_b=$(version_c))
    $(info version_b=$(version_d))

输出:

$ make -s
version_a=39
version_b=0
version_b=12
version_b=8

相关问题