Is it possible to make everything in a while loop run instantly?

Viewed 80

I have an infinite while loop. The while loop basically goes through every character in a file and stops when it gets to a certain character. For example, if trying to stop at "e" in abcdefghi (var=abcdefghi), then it will change i by 1 until "char={var:$i:1}" (my getchar function does this) sets char to e. (Then it sets b to 1)

b=0
while :
do
  ((i++))
  getchar -\"
  if [ $b == 1 ]; then
    break
  fi
done

The thing is, sometimes the space between where i currently is and the next quotation mark is big (like maybe 1000 characters until the next for that amount, it takes about a minute.). Is there a way to run the loop almost instantly? I mean instantly by less than 5 seconds.

Also, here is my getchar function

  getchar () { #stops loop when it detects char $1
    if ! [ -$2 == -++ ]; then
      char=${jsonfile:$i:1}
      if [ -$char == "$1" ]; then
        b=1
      fi
    else
      if ! [ -$char == "$1" ]; then
        char=${jsonfile:$(expr $i + 1):1}
        if [ -$char == "$1" ]; then
          b=1
        fi
        char=${jsonfile:$i:1}
      else
        char=
      fi
    fi
  }

If you need to look at the whole file, here it is on github https://github.com/0K9090/ScratchLang/blob/main/mainscripts/decompiler.sh

1 Answers

Try sed and an array:

var=abcdefghi

Cut junk part first:

$ sed 's/e.*/e/' <<< "$var"
abcde

Then add spaces in between:

$ sed 's/e.*/e/; s/./ &/g' <<< "$var"
 a b c d e

And now make an array out of this:

arr=( $(sed 's/e.*/e/; s/./ &/g' <<< "$var") )

The last item will be 'e':

$ echo ${arr[@]:(-1)}
e

And the number of items in array will be your desired number:

$ echo ${#arr[@]}
5

Without loop it'll be quite fast I suppose.

Related