从目录中递归获取文件

huangapple go评论44阅读模式
英文:

make; get files from dir recursively

问题

我需要将特定验证应用于我的测试文件,我们的项目使用 make,所以我也尝试使用 make 来做这件事。我遇到的问题是,我要么可以获取我的目录中第一级的所有测试文件,要么获取第二级及以下的测试文件:

TESTS = dir_1/**/test_*.py \
   dir_2/test_*.py

check_tests:
	set -x; for test_file in $(TESTS); do echo $$test_file; check_test $$test_file; done;

假设我们有以下目录结构:

dir_1
   test_one.py
   dir_1_1
      test_two.py
dir_2
   test_three.py
   dir_2_1
      test_four.py

这种方法将返回 dir_1/dir_1_1/test_two.py dir_2/test_three.py。我不想为每个目录编写这两个模式。是否有一种模式可以获取目录及其子目录中的所有匹配文件?

英文:

I need to apply a certain validation to my test files, our project uses make, so I'm trying to do that using make, too. The problem I'm running into is that I can either get all the test files in the first level of my dirs, or the second and lower:

TESTS = dir_1/**/test_*.py \
   dir_2/test_*.py

check_tests:
	set -x; for test_file in $(TESTS); do echo $$test_file; check_test $$test_file; done;

Suppose we have the following dir structure:

dir_1
   test_one.py
   dir_1_1
      test_two.py
dir_2
   test_three.py
   dir_2_1
      test_four.py

This approach will yield dir_1/dir_1_1/test_two.py dir_2/test_three.py. I don't want to have to write both patterns for each of the dirs. Is there a pattern I can use that will fetch all the matching files in a dir and its subdirectories?

答案1

得分: 1

“**” 表示“搜索所有子目录”,这是一些Shell的特殊功能,但不是POSIX Shell的功能。如果在系统上提供标准的POSIX Shell(例如Debian及其变种如Ubuntu)作为/bin/sh,则使用它的话,您的makefile将无法工作。即使在某些Shell上,它可以工作,通常您也必须指定一个特殊选项来启用它。实际上,从您获得的输出来看,它并没有真正起作用,它只被视为一个单独的*

在POSIX 中查找所有子目录中的文件的方式是使用find程序。您可以像这样做:

TEST_DIRS := dir_1 dir_2
TEST_FILES := $(foreach D,$(TEST_DIRS),$(shell find $D -name 'test_*.cpp' -print))

check_tests:
    set -x; for test_file in $(TEST_FILES); do echo $$test_file; check_test $$test_file; done

请注意,上面的makefile中已经将双星号(**)替换为了单星号(*),并添加了适用于makefile的语法。

英文:

The ** meaning "search all subdirectories" is a special feature of some shells, but it's not a feature of POSIX shells. By using it your makefile will not work on systems which provide a standard POSIX shell as /bin/sh (such as, for example, Debian and its variants like Ubuntu). Even with shells where it does work often you have to specify a special option to enable it. In fact it's not actually working for you as seen by the output you get: it's being treated just as a single *.

The POSIX way to find all files in subdirectories is to use the find program. You could do something like this:

TEST_DIRS := dir_1 dir_2
TEST_FILES := $(foreach D,$(TEST_DIRS),$$(find $D -name test_\*.cpp -print))

check_tests:
        set -x; for test_file in $(TEST_FILES); do echo $$test_file; check_test $$test_file; done

huangapple
  • 本文由 发表于 2023年6月19日 20:40:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76506715.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定