Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

word count of each line in a script

Tags:

bash

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 
like image 627
Jason Gagnon Avatar asked Feb 02 '12 03:02

Jason Gagnon


People also ask

How do you count words in a line?

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.

How do you count the number of lines in a shell?

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.

What is wc in script?

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.

How do you count lines with grep?

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.


2 Answers

In case you want to impress at the risk of getting caught for plagiarism:

 awk '$0="line"NR": "NF' imagine.txt
like image 158
SiegeX Avatar answered Nov 14 '22 21:11

SiegeX


printf "$line_num: $(echo $line | wc -w)"
like image 37
John Zwinck Avatar answered Nov 14 '22 22:11

John Zwinck