JBoy
JBoy

Reputation: 5735

How to use an expression as loop counter in bash?

I'm completely new in the Linux world, i-m using a Bash shell and practicing a bit. How can i perform a loop giving as counter an expression? For example looping through the amount of word in a file.

for n in(wc -w text.txt)
 do
   echo "word number $n"
 done

Unfortunately the above script its not working. The only way i have found so far is to first print the value of wc -w text.txt, then assign it to a variable and then loop:

wc -w text.txt
a=10   //result saw by wc -w text.txt
for((b=0; b<a; b++))
do
echo "$b"
done

The problem is that i need to retrieve the value of wc -c and asssing it directly to a variable, in case i have to write a script that runs automatically, the problem is that

a= wc -w test.txt

Will not work,

Any advice?

Upvotes: 5

Views: 5717

Answers (1)

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38032

A clean way to do this is

tmp=$(wc -w <text.txt)
for ((i=0; i<$tmp; i++))
do 
    echo $i; 
done

The <text.txt part is necessary, because normally, the output of the wc command is

wordcount1  INPUTFILE1
wordcount2  INPUTFILE2
...

The max value for i must equal the word count of your file, so you must take away the INPUTFILE1 part before your loop works as intended. Using an input stream < rather than a filename takes care of this issue.

Using a temp variable prevents wc from being called on each iteration.

Upvotes: 3

Related Questions