KSH检查字符串是否以substring开头

z4y*_*4ts 14 string shell ksh

我需要检查变量是否具有以指定子字符串开头的字符串值.

在Python中它将是这样的:

foo = 'abcdef'
if foo.startswith('abc'):
    print 'Success'
Run Code Online (Sandbox Code Playgroud)

检查Ksh中strig是否$foo以子字符串开头的最明确方法是什么bar

Aar*_*lla 25

这很简单,但看起来有点奇怪:

if [[ "$foo" == abc* ]]; then ...
Run Code Online (Sandbox Code Playgroud)

可以假设ksh会使用当前目录中的文件扩展模式,但是它会进行模式匹配.但是你需要这个[[.单身[无效.如果没有空白,则引号不是绝对必要的foo.


gle*_*man 17

也:

foo='abcdef'
pattern='abc*'

case "$foo" in
    $pattern) echo startswith ;;
    *) echo otherwise ;;
esac
Run Code Online (Sandbox Code Playgroud)


Pau*_*ce. 6

你也可以做正则表达式匹配:

if [[ $foo =~ ^abc ]]
Run Code Online (Sandbox Code Playgroud)

对于更复杂的模式,我建议使用变量而不是将模式直接放在测试中:

bar='^begin (abc|def|ghi)[^ ]* end$'
if [[ $foo =~ $bar ]]
Run Code Online (Sandbox Code Playgroud)