How to compute the range in Makefile

风格不统一 提交于 2019-12-24 09:57:29

问题


Here is my Makefile and the output, how to print the range like [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:


Here is pipeline of shell commands to get your job done:

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 = $1} p < $1-1{prnt(","); s = $1} {p = $1} END{prnt(ORS)}'

1-5,7,9-10

Commands are:

  1. printf to print each filename on separate lines
  2. sed to remove everything except digits
  3. sort to sort numerically to get the range in right sequence
  4. awk to set the range and format the results



回答2:


There are several approaches:

  1. If you know the maximum possible value: First, add SHELL=bash so that brace espansion works. Then use something like $(shell {1..10}), and pass that result through $(wildcard) to exclude non-existent files.
  2. Pipe lines through sort -n, again in $(shell).
  3. Pad numbers on the left with 0s, then sort normally.


来源:https://stackoverflow.com/questions/46288292/how-to-compute-the-range-in-makefile

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!