如何计算 Makefile 中的范围

How to compute the range in Makefile

这是我的 Makefile 和输出,如何打印像 [1-5, 7, 9-10] 这样的范围?

$ ls /tmp/foo
foo10.txt  foo1.txt  foo2.txt  foo3.txt  foo4.txt  foo5.txt  foo7.txt  foo9.txt

$ cat Makefile 
DIR1 := /tmp/foo/
COMMA :=,
EMPTY :=
SPACE := $(EMPTY) $(EMPTY)
VERSIONS := $(subst $(SPACE),$(COMMA),$(patsubst foo%,%,$(basename $(notdir $(wildcard $(DIR1)/foo*.txt)))))
all:
        $(info versions is [${VERSIONS}])

$ make
versions is [10,1,2,3,4,5,7,9]

有几种方法:

  1. 如果您知道最大可能值:首先,添加 SHELL=bash 以便大括号扩展有效。然后使用 $(shell {1..10}) 之类的东西,并将结果传递给 $(wildcard) 以排除不存在的文件。
  2. 管道线通过 sort -n,再次在 $(shell)
  3. 左边的数字用0s填充,然后正常排序。

这是完成工作的 shell 命令管道:

printf '%s\n' foo*[0-9].txt |
sed 's/[^0-9]*//g' |
sort -n |
awk 'function prnt(sep){printf "%s%s", s, (p > s ? "-" p : "") sep}
NR==1{s = } p < -1{prnt(","); s = } {p = } END{prnt(ORS)}'

1-5,7,9-10

命令是:

  1. printf 在单独的行上打印每个文件名
  2. sed 删除除数字以外的所有内容
  3. sort 按数字排序以获得正确顺序的范围
  4. awk 设置范围并格式化结果