views:

76

answers:

6

If I store a long string in a variable and need to test if the string would begin with the letters abc, what would be the most efficient way to test this?

Of course, you could echo the string and pipe it to grep/awk/sed or something like that but isn't there a more efficient way (which doesn't require to scan the whole string?)?

Can I use a case statement for this, like e.g.

case $var in
    ^abc) doSomething;;
esac

?

Greets, Oliver

+1  A: 

This should be efficient :

if [[ "$a" == abc* ]]
Amir Afghani
I don't think `[` supports globbing...
Nicolás
You might be right, it may be [[
Amir Afghani
You are right, I'll edit
Amir Afghani
+1  A: 

grep doesn't really need to scan the whole string. Just use echo "$string" | grep '^abc'.

If you really want efficiency, don't use a shell script.

Nicolás
+1 That's a good point. I think I'll stick to that and see if performance is actually a problem.
Helper Method
+3  A: 

In Bash, there's a substring operator:

mystring="abcdef blah blah blah"

first_three=${mystring:0:3}    

after which $first_three will contain "abc".

Jim Lewis
Really interesting, thanks.
Nicolás
+1  A: 
case "$var" in
  abc*) doSomething ;;
esac
Matthew Slattery
A: 

I'd use grep:

if [ ! -z `echo $string | grep '^abc'` ]

but for variety you cut use cut

if [ `echo $string | cut -c 1-3` = "abc" ]
Paul Creasey
+1  A: 

using shell internals is the more efficient way than calling external commands

case "$string" in
  abc* ) echo "ok";;
esac

Or if you have modern shell such as bash

if [ "${string:0:3}" = "abc" ] ;then
   echo "ok"
fi
ghostdog74