Skip to content

Traversing a directory using Makefile

I am making use of a makefile to traverse a directory , store the file names in a variable , extract the file number using regex and print the file number .

Below is the code block I am using :

1. set -e ;
2. for file in $$(MY_HOME)/mydir/python_files/ ;
3. do 
4. string =$${file} ;
5. [[ $$string =~ .*clause([0-9]*).py ]] ; 
6. file_num=$${BASH_REMATCH[1]} ; 
7. python $$(My_Home)/base_py_<file_num>.py ;
8. done ;

LINE 7 is the command in makefile I want to include in the for loop. I want the actual file_num in the above < file_num > placeholder (line 7). How can I do the same. Is there any alternative approach for the same ?

Thanks in advance



I would make a native make approach instead of looping in bash, like so:

$ cat Makefile
MY_HOME := myhome
CLAUSE_FILES_DIR := $(MY_HOME)/mydir/python_files

clause_files := $(wildcard $(CLAUSE_FILES_DIR)/*clause*.py)
clause_numbers := $(foreach clause_file,$(notdir $(, 
                    $(lastword $(subst clause, ,$(clause_file))))

.PHONY: execute-clause-%
execute-clause-%: $(MY_HOME)/ $(CLAUSE_FILES_DIR)/*
        echo python $<

all: $(addprefix execute-clause-,$(clause_numbers))

clause_files will keep all existing files matching the pattern. clause_numbers will process the file names by stripping extension and directory, then split on clause to get only the part between clause and extension.

execute-clause-% is a generic rule to run based on existence of a specific base_py_*.py script and a matching clause file. If one or the other does not exist, the rule will not be run.

Finally all rule executes all existing clauses. And since every processing is done by a separate rule, all of them might be executed in parallel by just running make -j.

Sample output:

## Preparation stage
$ mkdir -p myhome/mydir/python_files
$ for i in `seq 1 5`; do touch myhome/base_py_$; done
$ for i in `seq 1 5`; do touch myhome/mydir/python_files/${RANDOM}_clause$; done
$ touch myhome/mydir/python_files/  # Just to show it does not match
$ touch myhome/             # To demonstrate missing clause file

$ ls -R myhome/
myhome/:  mydir



## Execution
$ make -s
python myhome/
python myhome/
python myhome/
python myhome/
python myhome/

Note that neither nor did not cause running the rule.

User contributions licensed under: CC BY-SA
6 People found this is helpful