Lucia
Lucia

Reputation: 95

How To Split Up Digits Into Character Array

I'm a bit stuck with something. I have a for loop like this:

#!/bin/bash
for i in {10..15}
do

I want to obtain the last digit of the number, so if i is 12, I want to get 2. I'm having difficulties with the syntax though. I've read that I should convert it into a character array, but when I do something like:

j=${i[@]}
echo $j

I don't get 1 0 1 1 1 2 and so on...I get 10, 11, 12...How do I get the numbers to be split up so I can get the last one of i, when I don't always know how many digits will make up i (ex. it may be 1, or 10, or a 100, etc.)?

Upvotes: 3

Views: 707

Answers (3)

Frank
Frank

Reputation: 338

Trick is to treat $i like a string.

for i in {10..15}; do j="${i: -1}"; echo $j; done

Of course, you do not need to assign to a variable if you don't want to:

for i in {10..15}; do echo "${i: -1}"; done

Upvotes: 4

ashish_k
ashish_k

Reputation: 1581

This awk command could solve your problem:

awk '{print substr($0,length,1)}' test_file

I'm assuming that the numbers are saved in a file test_file

If you want to use for loop:

for i in `cat test_1`
do
echo $i |tail -c 2
done

Upvotes: 1

sjsam
sjsam

Reputation: 21965

This answer which uses GNU shell parameter expansion is the most sensible method, I guess.

However, you can also use the double parenthesis construct which allows C-style manipulation of variables in Bash.

for i in {10..15}
do
 (( j =  i % 10 )) # modulo 10 always gives the ones' digit
 echo $j
done

Upvotes: 1

Related Questions