英文:
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
).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论