我应该如何让 bash 3.2 找到通配符之间的模式
尝试将输入与包含警报词的文件进行比较,
read MYINPUT
alertWords=( `cat "AlertWordList" `)
for X in "${alertWords[@]}"
do
# the wildcards in my expression do not work
if [[ $MYINPUT =~ *$X* ]]
then
echo "#1 matched"
else
echo "#1 nope"
fi
done
Trying to compare input to a file containing alert words,
read MYINPUT
alertWords=( `cat "AlertWordList" `)
for X in "${alertWords[@]}"
do
# the wildcards in my expression do not work
if [[ $MYINPUT =~ *$X* ]]
then
echo "#1 matched"
else
echo "#1 nope"
fi
done
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
=~
运算符处理正则表达式,因此要像您想要的那样进行通配符匹配,语法如下所示:但是,由于这是正则表达式,因此不需要这样做,因为它暗示它可以位于字符串中的任何位置(除非它使用
^
和/或$
锚定,所以这应该足够了:请注意,如果您的“单词”碰巧包含正则表达式元字符,那么这可能会做奇怪的事情。
The
=~
operator deals with regular expressions, and so to do a wildcard match like you wanted, the syntax would look like:However, since this is regex, that's not needed, as it's implied that it could be anywhere in the string (unless it's anchored using
^
and/or$
, so this should suffice:Be mindful that if your "words" happen to contain regex metacharacters, then this might do strange things.
我会在这里避免
=~
因为正如 FatalError 指出的那样,它将把$X
解释为正则表达式,这可能会导致令人惊讶的错误(特别是因为它是一个扩展的正则表达式)表达式,因此它比标准 grep 语法有更多的特殊字符)。相反,您可以只使用
==
因为 bash 将==
的 RHS 视为通配模式:我还在您的
alertWords 中删除了 cat 的使用
赋值,因为它使文件在 shell 内读取,而不是生成另一个进程来执行此操作。I'd avoid
=~
here because as FatalError points out, it will interpret$X
as a regular expression and this can lead to surprising bugs (especially since it's an extended regular expression, so it has more special characters than standard grep syntax).Instead, you can just use
==
because bash treats the RHS of==
as a globbing pattern:I've also removed a use of cat in your
alertWords
assignment, as it keeps the file reading inside the shell instead of spawning another process to do it.如果您想使用模式而不是正则表达式进行匹配,可以使用
case
:If you want to use patterns, not regexes for matching, you can use
case
: