Check the first 3 characters in the string looong (effective)

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

Of course, you can repeat the line and pass it to grep / awk / sed or something like that, but is there a more efficient way (which does not require scanning the entire line?)?

Can I use the case statement for this, for example, for example.

case $var in
    ^abc) doSomething;;
esac

?

Cheers, Oliver

+3
source share
6 answers

grepreally don't need to scan the entire line. Just use it echo "$string" | grep '^abc'.

If you really need efficiency, do not use a shell script.

+1
source

Bash :

mystring="abcdef blah blah blah"

first_three=${mystring:0:3}    

$first_three "abc".

+3

This should be effective:

if [[ "$a" == abc* ]]
+1
source
case "$var" in
  abc*) doSomething ;;
esac
+1
source

Using shell internal shells is more efficient than calling external commands

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

Or if you have a modern shell like bash

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

I would use grep:

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

but for a change you are reducing the use of cut

if [ `echo $string | cut -c 1-3` = "abc" ]
0
source

Source: https://habr.com/ru/post/1728241/


All Articles