3

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
 echo
((aux++))
done

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. – Puspharaj Selvaraj Mar 5 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 at 11:09
14

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).

Use

awk '{ print NF, $0 }' inputfile

With your sample input, this will print

4 drinks water cola fanta
3 fruit banana orange
  • The more cryptic awk '$0=NF" "$0' inputfile is a shorter solution. – Isaac Mar 5 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 at 11:05
  • Thanks everyone for their advices. I didn't know about awk, thanks! – Multi Mar 5 at 17:25
3

In Bash and wc:

IFS=$'\n'
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.

  • Thanks, I was aware about WC -l for lines but not for words, thanks! – Multi Mar 5 at 17:25

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.