我正在使用Ubuntu系统shell,而不是bash,我发现常规方式无法正常工作:
#!/bin/sh
string='My string';
if [[ $string =~ .*My.* ]]
then
echo "It's there!"
fi
Run Code Online (Sandbox Code Playgroud)
错误[[:找不到!
我该怎么做才能解决这个问题?
gav*_*koa 19
为什么使用grep这样简单的模式?通过Sh内置匹配引擎避免不必要的fork:
case "$value" in
*XXX*) echo OK ;;
*) echo fail ;;
esac
Run Code Online (Sandbox Code Playgroud)
它符合POSIX标准.Bash 为此简化了语法:
if [[ "$value" == *XXX* ]]; then :; fi
Run Code Online (Sandbox Code Playgroud)
Chr*_*lan 18
这[[ ... ]]
是一种打击主义.您可以通过只使用让您的测试壳不可知grep
与正常if
:
if echo "$string" | grep -q "My"; then
echo "It's there!"
fi
Run Code Online (Sandbox Code Playgroud)
你可以使用expr
:
if expr "$string" : "My" 1>/dev/null; then
echo "It's there";
fi
Run Code Online (Sandbox Code Playgroud)
这适用于sh
和bash
.
作为一个方便的功能:
exprq() {
local value
test "$2" = ":" && value="$3" || value="$2"
expr "$1" : "$value" 1>/dev/null
}
# Or `exprq "somebody" "body"` if you'd rather ditch the ':'
if exprq "somebody" : "body"; then
echo "once told me"
fi
Run Code Online (Sandbox Code Playgroud)
引用自man expr
:
STRING : REGEXP
anchored pattern match of REGEXP in STRING
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
19579 次 |
最近记录: |