Home > Enterprise >  How to split a word in the given positive or negative fraction
How to split a word in the given positive or negative fraction

Time:12-06

So for example I have a word: swimming and running. Swimming consist of 8 letters and running of seven, if there is a given fraction, like 3/4 for swimming and -2/7 for running. It would need to give me swimmi and ng because the fraction given to running is negative so it needs to start at the end.

I know it is with this command

echo ${word:0:${#word}*$frac} 

And I get

swimmi
ru

But this doesn't work for a negative number and I expected this

swimmi
ng

CodePudding user response:

With the distinction of negative or positive fraction.

word="running"
frac=-2/7

if [[ $frac =~ ^- ]]; then
  # negative
  echo "${word:${#word}*$frac}"
else
  # positive
  echo "${word:0:${#word}*$frac}"
fi

Output:

ng
  • Related