KSH check if string starts with substring
Asked Answered
O

4

16

I need to check if the variable has value of string which starts with specified substring.

In Python it would be something like this:

foo = 'abcdef'
if foo.startswith('abc'):
    print 'Success'

What is the most explicit way to check in Ksh whether strig $foo starts with substring bar?

Obscene answered 2/11, 2010 at 17:27 Comment(0)
T
27

It's very simple but looks a bit odd:

if [[ "$foo" == abc* ]]; then ...

One would assume that ksh would expand the pattern with the files in the current directory but instead, it does pattern matching. You need the [[, though. Single [ won't work. The quotes are not strictly necessary if there are no blanks in foo.

Tawnytawnya answered 2/11, 2010 at 17:35 Comment(4)
Inside double brackets, you don't need the quotes even if $foo is null or unset.Loudmouthed
The solution looks exactly like what I was looking for. But unfortunately it doesn't work in my ksh. It looks like ksh88, I guess too old for such tricks.Obscene
What if $foo has "=" in it?Salter
@user443854: BASH expansion works in such a way that the if command gets the contents of foo as a single parameter, so it doesn't matter. And the if command only looks for a parameter which is exactly =, it doesn't try to split parameters further.Tawnytawnya
D
17

Also:

foo='abcdef'
pattern='abc*'

case "$foo" in
    $pattern) echo startswith ;;
    *) echo otherwise ;;
esac
Demisec answered 2/11, 2010 at 19:1 Comment(2)
You certainly don't need the interim variable. case $foo in 'abc'* ) echo yes ;; esacVermicelli
portable back to solaris 9 /bin/sh and @tripleee's simplification above worksGittel
L
6

You can also do regex matching:

if [[ $foo =~ ^abc ]]

For more complex patterns, I recommend using a variable instead of putting the pattern directly in the test:

bar='^begin (abc|def|ghi)[^ ]* end$'
if [[ $foo =~ $bar ]]
Loudmouthed answered 2/11, 2010 at 18:35 Comment(0)
M
0
#!/bin/ksh
case ${foo:0:3} in
    abc) echo success;;
      *) echo failure;;
esac
Manuscript answered 13/4, 2022 at 20:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.