Shell – Count the number of words of particular length from a file

shelltext processing

I've used the below command to count the number of words in a file:

tr ' ' '\n' < Filename | grep -c "WORD"

This returns the word list with counter. Now I want to count the number of words of a particular length. For example, given a file with these contents:

employee paresh emp employee jayesh hitesh

When I run the shell script with argument 6, it should display/count words with 6 characters (paresh, jayesh, and hitesh, with count 3). How can I do that?

Best Answer

If you grep for the regular expression ^.{6}$ it will return lines with exactly six characters:

$ tr ' ' '\n' < Filename | grep '^.\{6\}$'
paresh
jayesh
hitesh

$ tr ' ' '\n' < Filename | grep -c '^.\{6\}$'
3
Related Question