I have a text file called "shoplist.txt" which one have:

drinks water cola fanta
fruit banana orange

And I want to get how many items per line I have. I'm able to extract drinks and fruit with function "cut" but how can I count how many words I have in each line?

My actually code is:

fileLine=`cat file.txt`
#Here I get each line saving it to fileLine
for line in $fileLine; do

But this code dosen't work because it save to %fileLine each work (drinks, then water,then cola,...)

How can I get the first line and then count the words on that line?

  • wc would do the necessary job in a loop. – EngineSense Mar 5 '19 at 5:31
  • Is the output of the awk script in the answer what you want to have? If not, what exactly do you want to get? – Bodo Mar 5 '19 at 11:09

If you can use awk, NF is the number of fields in the current line (by default, a field is a word delimited by any amount of whitespace).


awk '{ print NF, $0 }' inputfile

With your sample input, this will print

4 drinks water cola fanta
3 fruit banana orange
| improve this answer | |
  • The more cryptic awk '$0=NF" "$0' inputfile is a shorter solution. – Isaac Mar 5 '19 at 4:14
  • @Isaac: Really ? Is shorter better ? In this specific case Bodo's answer is just the answer to OP, ... and [s]he beat us all to it. :-[ – Cbhihe Mar 5 '19 at 11:05
  • Thanks everyone for their advices. I didn't know about awk, thanks! – Multi Mar 5 '19 at 17:25

In Bash and wc:

while read line; do
    wc -w <<< "$line"
done < file.txt

wc counts lines, words, bytes in files. With a shell loop you can make it count words in a line.

| improve this answer | |
  • Thanks, I was aware about WC -l for lines but not for words, thanks! – Multi Mar 5 '19 at 17:25
  • Upvote. Such a simple job no need to bother awk – Bruce Nov 3 '19 at 21:52
  • Sure, @bruce. For 10,000 line file, why run awk when you can run 10,000 consecutive wc processes? – Paul_Pedant Nov 28 '19 at 19:02
  • Yes, you are right @Paul_Pedant. If performance becomes an issue, we definitely will go a programming language, such as awk, perl or python, or C who knows. But before that, I'd like to keep it simple enough. – Bruce Dec 1 '19 at 0:30
  • @bruce: But Bodo published a one-liner that does what the 4-line shell does, but probably 200 times faster, and it got 14 upvotes. It's hardly a "programming language" issue: it contains one simple command. How would you explain the simplicity of <<< in the Bash version, for example? – Paul_Pedant Dec 1 '19 at 19:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.