首页 > 解决方案 > 使用 makefile 阅读和跳过注释行的更好方法

问题描述

此代码片段适用于“dirlist.txt”中的给定目录列表

DIR_LIST = "dirlist.txt"

exclude_legacy:
    @echo "=== Checking dirs to exclude..."
    while read -r dirto_exclude; \
    do \
        if [[ "$${dirto_exclude}" = \#.* ]]; then \
            continue; \
        else \
            echo "Exclude this dir, $${dirto_exclude}"; \
            rm -rf $${dirto_exclude}; \
        fi \
    done < $(DIR_LIST)

有两个问题:

  1. 有兴趣知道在 make 的内置函数的帮助下是否有更好的方法来实现相同的目标。

  2. 运行“make -s -f Makefile”会清除“dirlist.txt”中给出的所需目录。但是,echo 语句(在 else 块中)的输出也会打印带有注释的行,这些注释在给出的条件中被跳过'如果'块。我希望输出只包含要清除的那些目录名,这与预期的一样。

为什么是这样?

谢谢,维吉

标签: makefilegnu-make

解决方案


Make 用于“制作”文件,而不是删除它们,所以不要对这种漂亮的东西抱有希望。

GNU Make (4.2) 具有file读取文件的功能,请参阅此答案

DIR_LIST := $(file < dirlist.txt)

看起来您在前导“#”上有一些类似注释的语法。在那种情况下,我会尝试使用 grep(未测试):

DIR_LIST := $(shell grep -v "#*" dirlist.txt)

接下来,我们可以rm -rf用于在一次调用中删除所有文件:

exclude_legacy:
    @echo Removing directories "$(DIR_LIST)"
    rm -rf $(DIR_LIST)

如果DIR_LIST显示为空,则rm命令将失败。如果您需要它来工作,我会尝试 xargs 。


推荐阅读