I have to write a script to read each line using a while loop and count the number of words in each line. So far i can get the total number of lines and the text for each on its own line. I am having trouble using the wc -w command to count the number of words for each line and display it. when i put it on the same line as the printf statement is gives an inaccurate count. I have to pipe the text tile to the script so it will count the words, for example: cat file.txt | word_count.sh
any suggestions?
code:
#!/bin/bash
line_num=1
while read line;do
printf "line $line_num: $line"
((line_num++))
done
results:
cat imagine.txt | word_counts.sh
line1: magine there's no countries
line2: It isn't hard to do
line3: Nothing to kill or die for
line4: And no religion too
line5: Imagine all the people living life in peace
1 Answer