Jamie
Jamie

Reputation: 7431

How can I rewrite this BASH for loop not using the `seq` command?

I was trying to write a BASH loop of the form:

~/$ for i in {1..$(grep -c "match" file)} ; do echo $i ; done
{1..20}

where I was hoping it would produce counted output. So I tried this instead:

~/$ export LOOP_COUNT=$(grep -c "match" file)
~/$ for i in {1..$LOOP_COUNT} ; do echo $i ; done
{1..20}

What I fell back to using was:

~/$ for i in $(seq 1 1 $(grep -c "match" file)) ; do echo $i ; done
1
2
3
...
20

Perfect! But how can I get that behaviour without using seq?

Upvotes: 0

Views: 214

Answers (3)

user unknown
user unknown

Reputation: 36260

Here is a recursive solution:

loop () {
    i=$1
    n=$2 
    echo $i
    ((i < n)) && loop $((i+1)) $n
}

LOOP_COUNT=$(grep -c "Int" sum.scala)

loop 1 $LOOP_COUNT

Upvotes: 0

choroba
choroba

Reputation: 242103

According to bash documentation

A sequence expression takes the form {x..y[..incr]}, where x and y are either integers or single characters, and incr, an optional increment, is an integer.

You can still use eval in other cases, but Mithrandir's advice is probably faster.

eval "for i in {1..$(grep -c 'match' file)} ; do echo \$i ; done"

Upvotes: 3

Mithrandir
Mithrandir

Reputation: 25387

Have you tried this?

max=$(grep -c "match" file)

for (( c=1; c <= $max; c++ ))
do
    echo $c
done

Upvotes: 4

Related Questions