Question

Can anyone tell me how to do it? My code is as follows:

#!/bin/bash
typeset -i count=0;
for ((i=1;i<=1232;i++));
do
if [                             ]; then
count=count+1; 
fi
done
echo $count

333 counts as one occurrence.

Was it helpful?

Solution

Try this:

#!/bin/bash
typeset -i count=0;
for ((i=1;i<=1232;i++));
do
    if [[ "$i" =~ .*3.* ]]; then
        count=count+1 
    fi
done
echo $count

This code performs a regex searching for 3 in i as the for loop progresses.

Incidentally, the answer is 315.

If you need to use grep:

#!/bin/bash
typeset -i count=0;
for ((i=1;i<=1232;i++));
do
    if grep -q 3 <<<$i; then
        count=count+1 
    fi
done
echo $count

It's a lot slower, though.

OTHER TIPS

To count how many numbers from 1 to 1232 have at least one 3 in their decimal representations (so 333 is counted once):

$ seq 1232 | grep -c 3
315

To count the total number of 3s (so 333 is counted 3 times):

$ seq 1232 | sed 's/./& /g' | fmt -w 1 | grep -c 3
346
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top