Issue
I want to take numbers as command-line arguments and prints the count of numbers that end with 0, 1, 2, etc. up to 5.
Example:
Expected Output:
Digit_ends_with count
0 0
1 0
2 2
3 0
4 2
5 1
Mt Attempt:
read -a integers for i in ${integers[@]} do if [[ grep -o '[0-9]' $i ]] count=$(grep -c $i) if [ "$count" -ge "0" ] then
echo "Digit_ends_with" $i echo -e "Count ""$count" fi fi done
But this is not working. How I can achieve this requirement?
Solution
Would you please try the following:
#!/bin/bash
for i in "$@"; do # loop over arguments
(( count[i % 10]++ )) # index with the modulo 10
done
printf "%s %s\n" "Digit_ends_with" "count" # header line
for (( i = 0; i < 6; i++ )); do # loop between 0 and 5
printf "%d\t\t%d\n" "$i" "${count[$i]}" # print the counts
done
Result of ./test.sh 12 14 12 15 14
:
Digit_ends_with count
0 0
1 0
2 2
3 0
4 2
5 1
Answered By - tshiono Answer Checked By - Katrina (WPSolving Volunteer)