5

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?

3
  • a=wc -w test.txt should be in backticks or $() to work and no space around =, i.e. a=$(wc -w test.txt) Commented Jul 6, 2012 at 9:08
  • a=$(wc -c test.txt) or a=$`wc -c test.txt` will assign to a a text value: '6 test.txt', if you try to iterate this value, you of course then will get an error (arithmetic expression needed) Commented Jul 6, 2012 at 9:15
  • Use a=$(wc -w < test.txt) to remove the filename in wc output. Commented Dec 10, 2012 at 12:14

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

(set -v; your code) shows that wc is called for each iteration; use a variable instead
Thanks! added your suggestions to the answer.
is the dollar sign in this case used as indicator for an expression evaluation?
@JBoy Yes, the $(...) notation works the same as backquoting in bash

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.