Search code examples
makefile

How to split a dynamic string and assign variables to each word?


I have a requirement to capture a test name from a path and use it to create a directory using makefile. Below is the code which i tried so far. Below code working for fixed "test_path" length.

%cat Makefile

    test_path := /dir1/dir2/dir3/test.sv

test_split := $(subst /, ,$(test_path:v%=%))

test_a := $(word 1,$(test_split))
test_b := $(word 2,$(test_split))
test_c := $(word 3,$(test_split))
test_d := $(word 4,$(test_split))
test_d_split := $(subst ., ,$(test_d:v%=%))
test_d_1 := $(word 1,$(test_d_split))

all:
    echo test_split = $(test_split)
    echo test_a = $(test_a)
    echo test_b = $(test_b)
    echo test_c = $(test_c)
    echo test_d = $(test_d)
    echo test_d = $(test_d)
    echo test_d_1 = $(test_d_1)
    mkdir $(test_d_1)

We are successfully creating a test directory using the above code, but we need to handle paths of different lengths. How can we do that?

Results:

used fixed length test_path := /dir1/dir2/dir3/test.sv -> working fine

if test_path is updated test_path := /dir1/dir2/dir3/dir4/test.sv % mkdir dir4 -> creating dir4 as directory.


Solution

  • What you want to achieve is not 100% clear. If the test directory you want to create is the filename with all suffixes removed (e.g., test when test_path = a/b/c/test.1.2.3) and if you use GNU make you could try:

    all:
        mkdir -p $(word 1,$(subst ., ,$(notdir $(test_path))))
    

    Note the -p option of mkdir to ignore the error when the directory already exists.