我在input.txt中有以下内容:
EA06\\?\.LFRFLB\\?\..*
Run Code Online (Sandbox Code Playgroud)
我想知道这个模式是否与以下字符串匹配:
EA06.LFRFLB.SHELLO
Run Code Online (Sandbox Code Playgroud)
然后我编码:
MY_STRING="EA06.LFRFLB.SHELLO"
REGEX=$(cat input.txt) # EA06\\?\.LFRFLB\\?\..*
if [[ "${MY_STRING}" =~ "${REGEX}" ]]; then
echo "FOUND"
else
echo "NOT FOUND"
fi
if [[ "${MY_STRING}" =~ EA06\\?\.LFRFLB\\?\..* ]]; then
echo "FOUND"
else
echo "NOT FOUND"
fi
Run Code Online (Sandbox Code Playgroud)
结果:
NOT FOUND
FOUND
Run Code Online (Sandbox Code Playgroud)
这里有什么问题?为什么第一个if不正确?解决它的最佳方法是什么?
问题是你引用了二元运算符的RHS上的变量,=~这导致变量替换被视为文字文本而不是正则表达式.你需要说:
if [[ "${MY_STRING}" =~ ${REGEX} ]]; then
Run Code Online (Sandbox Code Playgroud)
引自手册:
Run Code Online (Sandbox Code Playgroud)An additional binary operator, =~, is available, with the same prece? dence as == and !=. When it is used, the string to the right of the operator is considered an extended regular expression and matched accordingly (as in regex(3)). The return value is 0 if the string matches the pattern, and 1 otherwise. If the regular expression is syntactically incorrect, the conditional expression's return value is 2. If the shell option nocasematch is enabled, the match is performed without regard to the case of alphabetic characters. Any part of the pattern may be quoted to force it to be matched as a string.
特别注意最后一行:
可以引用模式的任何部分以强制它作为字符串匹配.
| 归档时间: |
|
| 查看次数: |
75 次 |
| 最近记录: |