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
To count the number of words in only part of your document, select the text you want to count. Then on the Tools menu, click Word Count. Just like the Word desktop program, Word for the web counts words while you type.
Use wc –lines command to count the number of lines. Use wc –word command to count the number of words. Print the both number of lines and the number of words using the echo command.
wc. wc stands for Word Count, although it can also count characters and lines. This makes it a flexible tool for counting any kind of items.
Using grep -c alone will count the number of lines that contain the matching word instead of the number of total matches. The -o option is what tells grep to output each match in a unique line and then wc -l tells wc to count the number of lines. This is how the total number of matching words is deduced.
In case you want to impress at the risk of getting caught for plagiarism:
awk '$0="line"NR": "NF' imagine.txt
printf "$line_num: $(echo $line | wc -w)"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With