You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Makefile如何查找字符串子串并结合if条件进行判断?

Makefile 字符串子串检查实现方案

你的需求是检查一个字符串是否包含指定子串,预期匹配逻辑如下:

  • "abc" in "abc" # True
  • "ab" in "abc" # True
  • "x" in "abc" # False

你之前用findstring的写法未得到预期结果,其实findstring本身支持子串匹配,只是写法可能有误。以下是几种更可靠的简单实现方法:

方法1:正确使用Makefile的findstring函数

findstring的作用是在目标字符串中查找子串,找到则返回子串本身(非空),找不到返回空。可以结合Makefile原生条件判断或Shell命令实现:

用Makefile原生条件判断

check_substring:
    ifeq ($(findstring ab,abc),ab)
	    @echo "YES"
    else
	    @echo "NO"
    endif

在Shell命令中调用

check_substring:
    if [ -n "$(findstring ab,abc)" ]; then \
	    echo "YES"; \
    else \
	    echo "NO"; \
    fi

注意:findstring的语法是$(findstring 子串,目标字符串),参数间的逗号是分隔符,不要写到字符串内容里。

方法2:使用Shell原生字符串匹配(推荐)

在Makefile的Shell命令中直接用Bash的模式匹配,写法更直观:

check_substring:
    target_str="abc"; search_str="ab"; \
    if [[ $$target_str == *"$$search_str"* ]]; then \
	    echo "YES"; \
    else \
	    echo "NO"; \
    fi

这里用$$转义Shell变量,避免被Makefile提前解析。

方法3:借助grep命令判断

利用grep的静默模式检查子串是否存在,通过退出码判断结果:

check_substring:
    echo "abc" | grep -q "ab"; \
    if [ $$? -eq 0 ]; then \
	    echo "YES"; \
    else \
	    echo "NO"; \
    fi

-q参数让grep不输出内容,仅返回退出码(找到子串时为0,未找到时非0)。

内容的提问来源于stack exchange,提问作者Meroz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 15:53:30