Thursday, 6 February 2014

[Makefile] filter unnecessary string and extract id number from a list of strings

For example, here’s a list of strings tst2b tst2222 tst22b 222b test tst22b2 tst222_ tst2333 tsta223. I want to only keep the string tst2222 tst2333 which starts with tst and follows with number, and no other string allowed. Besides, I will extract the id 2222 and 2333, and finally make them a comma separate list 2222,2333.
TEST_NAMES := tst2b tst2222 tst22b 222b test tst22b2 tst222_ tst2333 tsta223

# get the test id but excluded the case which doesn't have prefixed 'tst'
TST_IDS := $(foreach test,$(filter tst%,$(TEST_NAMES)), $(subst tst,,$(test)))

comma := ,
empty :=
space := $(empty) # 
# Comma separate test id lists, such as 123,2256,2256b
TST_IDS_COMMA_T := $(subst $(space),$(comma),$(strip $(TST_IDS)))

# Only keep the numbers and exclude the test which has the word [a-zA-Z_] in its id.
TST_IDS_COMMA := $(shell echo $(TST_IDS_COMMA_T) | sed 's/[^,]*[a-zA-Z_][^,]*//g; s/,,*,/,/g; s/^,//g; s/,$$//g')
  • filter function will only keep the string which begins with tst
  • subst will replace tst with empty, which removes the tst
  • foreach will recursively loop each test after filter
  • Second subst replace space ` with comma,`
  • The $TST_IDS_COMMA_T is like 2222,22b2,2333. sed will substitute the string which has alphabet [a-zA-z] and underline _ with empty, then replace multiple comma such as ,,, with one comma ,. The leading comma , and comma in the end of line are also removed.

No comments :

Post a Comment