Makefile. 如何在给定字符串中查找子字符串并在if条件中使用它。

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

Makefile. How do I find substring for given string and use it with if condition

问题

Case 1: "abc" in "abc" # True

Case 2: "ab" in "abc" # True

Case 3: "x" in "abc" # False

if [[ "abc" == *ab* ]]; then \
    echo "YES"; \
else \
    echo "NO"; \
fi;

YES

似乎 findstring 只匹配整个单词,而不是搜索子字符串(对于 Case 2 来说是不正确的)。有其他更简单的方法吗?

英文:

I'm trying to check if given string contains another. It should go like:

Case 1: "abc" in "abc" # True

Case 2: "ab" in "abc" # True

Case 3: "x" in "abc" # False

if test $(findstring "ab", "abc"); then \
    echo "YES"; \
else \
    echo "NO "; \
fi;

# NO

It seems that findstring is matching words only but not searching substrings (it is not correct for Case 2). Is there another simple way to do it?

答案1

得分: 1

你混合了make的语法和shell的语法。一般来说,你应该在规则(recipes)中使用shell的语法。

目标: 先决条件
    case "abc" in *"ab"*) echo yes;; *) echo no;; esac

如果需要更多的变化,也可以参考 https://stackoverflow.com/questions/229551/how-to-check-if-a-string-contains-a-substring-in-bash

[,也就是test命令,有点脆弱。如果你知道你的shell实际上是Bash,你可以使用[[;但你必须另外告诉make这一点(SHELL := /bin/bash),这显然会降低你的代码的可移植性。

另一个目标: 其他先决条件
    if [[ "abc" = *"ab"* ]]; then echo yes; else echo no; fi
    # 如果命令很简单,还可以使用一个方便的缩写:
    [[ "abc" = *"ab"* ]] && echo yes || echo no

你在使用findstring时的问题是"ab"实际上不是"abc"的子字符串(它是"ab"c的子字符串)。

英文:

You are mixing make syntax and shell syntax. Generally, you want to use shell syntax in recipes.

target: prerequisites
	case "abc" in *"ab"*) echo yes;; *) echo no;; esac

For further variations, see also https://stackoverflow.com/questions/229551/how-to-check-if-a-string-contains-a-substring-in-bash

The [ aka test command is somewhat brittle. If you know your shell is actually Bash, you can use [[; but then you separately have to tell make that (SHELL := /bin/bash) and this obviously makes your code less portable.

othertarget: other prereqs
	if [[ "abc" = *"ab"* ]]; then echo yes; else echo no; fi
	# if the commands are simple, a convenient shorthand:
	[[ "abc" = *"ab"* ]] && echo yes || echo no

Your problem with findstring is that "ab" really isn't a substring of "abc" (it would be a substring of "ab"c).

huangapple
  • 本文由 发表于 2023年3月9日 17:27:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75682645.html
匿名

发表评论

匿名网友

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

确定