ksh - 检查字符串是否有模式
ksh - check if String has a pattern
我有一串命令如下:
CMD_LAUNCH="launch.sh \
-v $ABC_VERSION \
-p something \
-X $MAX_HEAP_SPACE_PARAM \
-Dpersist false \
-DanotherPasram Abc"
我将在 ksh 中启动此命令,如下所示:
$CMD_LAUNCH
如何确保命令有 -Dpersist false
?
我想介绍 -Dpersist 和 false 之间可以没有空格的情况。但我的尝试未能实现。
尝试 1)
if [[ "$CMD_LAUNCH" = *"Dpersist\s+false"* ]]
then
echo "It's there!"
else
echo "It's not there!"
fi
我想测试命令中是否存在 Dpersist false
。
解决方案 1:
if [[ "$CMD_LAUNCH" == *+(Dpersist+(\s)false)* ]]
then
echo "It's there!"
else
echo "It's not there!"
fi
Ksh 的模式匹配与正则表达式不同,因为它总是匹配整个字符串——就像正则表达式以 ^
开头并以 $
结尾。
因此,您必须用星号将本身包含在括号中的模式括起来。 *
匹配任何字符序列。
每个模式前面的 +
表示匹配 1 次或多次出现的模式。
解决方案 2:
另一种选择是使用 =~
运算符:
if [[ "$CMD_LAUNCH" =~ Dpersist\s+false ]]
then
echo "Its there!"
else
echo "Its not there!"
fi
=~
使用正则表达式语法。
资源
有关更多示例,请参阅
- http://blog.fpmurphy.com/2009/01/ksh93-regular-expressions.html
- http://honglus.blogspot.de/2010/03/regular-expression-in-condition.html
- https://docstore.mik.ua/orelly/unix3/korn/ch04_05.htm
旁注
另请查看 ShellCheck,它有助于发现您的 shell 脚本中的错误。
我有一串命令如下:
CMD_LAUNCH="launch.sh \
-v $ABC_VERSION \
-p something \
-X $MAX_HEAP_SPACE_PARAM \
-Dpersist false \
-DanotherPasram Abc"
我将在 ksh 中启动此命令,如下所示:
$CMD_LAUNCH
如何确保命令有 -Dpersist false
?
我想介绍 -Dpersist 和 false 之间可以没有空格的情况。但我的尝试未能实现。
尝试 1)
if [[ "$CMD_LAUNCH" = *"Dpersist\s+false"* ]]
then
echo "It's there!"
else
echo "It's not there!"
fi
我想测试命令中是否存在 Dpersist false
。
解决方案 1:
if [[ "$CMD_LAUNCH" == *+(Dpersist+(\s)false)* ]]
then
echo "It's there!"
else
echo "It's not there!"
fi
Ksh 的模式匹配与正则表达式不同,因为它总是匹配整个字符串——就像正则表达式以 ^
开头并以 $
结尾。
因此,您必须用星号将本身包含在括号中的模式括起来。 *
匹配任何字符序列。
每个模式前面的 +
表示匹配 1 次或多次出现的模式。
解决方案 2:
另一种选择是使用 =~
运算符:
if [[ "$CMD_LAUNCH" =~ Dpersist\s+false ]]
then
echo "Its there!"
else
echo "Its not there!"
fi
=~
使用正则表达式语法。
资源
有关更多示例,请参阅
- http://blog.fpmurphy.com/2009/01/ksh93-regular-expressions.html
- http://honglus.blogspot.de/2010/03/regular-expression-in-condition.html
- https://docstore.mik.ua/orelly/unix3/korn/ch04_05.htm
旁注
另请查看 ShellCheck,它有助于发现您的 shell 脚本中的错误。