6

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?

2
  • wc would do the necessary job in a loop. 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
20

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
3
  • 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
4

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.

6
  • 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? 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? 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.