How to count words in a line
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
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.