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?
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.
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.
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.
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
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