开发者

Test the first 3 chars in a looong string (efficiently)

开发者 https://www.devze.com 2022-12-16 18:29 出处:网络
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?

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


In Bash, there's a substring operator:

mystring="abcdef blah blah blah"

first_three=${mystring:0:3}    

after which $first_three will contain "abc".


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.


case "$var" in
  abc*) doSomething ;;
esac


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


This should be efficient :

if [[ "$a" == abc* ]]


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" ]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号