Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count number of words from String using shell

Tags:

bash

I want to count number of words from a String using Shell.

Suppose the String is:

input="Count from this String" 

Here the delimiter is space ' ' and expected output is 4. There can also be trailing space characters in the input string like "Count from this String ".

If there are trailing space in the String, it should produce the same output, that is 4. How can I do this?

like image 382
Yogesh Ralebhat Avatar asked Feb 27 '13 09:02

Yogesh Ralebhat


People also ask

How do you count words in 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.

How do you count words in Unix?

The wc (word count) command in Unix/Linux operating systems is used to find out number of newline count, word count, byte and characters count in a files specified by the file arguments. The syntax of wc command as shown below.

How do you get the count of occurrences of a particular string in Unix?

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.


1 Answers

echo "$input" | wc -w 

Use wc -w to count the number of words.

Or as per dogbane's suggestion, the echo can be got rid of as well:

wc -w <<< "$input" 

If <<< is not supported by your shell you can try this variant:

wc -w << END_OF_INPUT $input END_OF_INPUT 
like image 66
Tuxdude Avatar answered Sep 21 '22 22:09

Tuxdude