Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
up vote 8 down vote accepted

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

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

$ tr ' ' '\n' < Filename | grep -c '^.\{6\}$'
share|improve this answer
Thanx for the support, it is running fine !! but can you please let me know about this : .\{6\} , that you have used with grep command. – Paresh Mayani Jan 3 '11 at 7:39
what about \ sign before { and } ?? please – Paresh Mayani Jan 3 '11 at 10:24
@Paresh Otherwise grep will look for { and } symbols, but not 6 repetitions of preceeding pattern. – alex Jan 3 '11 at 11:50
Argh. I accidentally deleted a comment trying to edit it; sorry whoever's that was. @Paresh As that comment pointed out, it's to escape the braces so they're treated as part of the regular expression (X{Y} means "find the X character Y times"); without the escapes it searches for actual braces – Michael Mrozek Jan 4 '11 at 15:28
thanx a lot for such helpful hints and answer. Thanx once again – Paresh Mayani Jan 5 '11 at 6:04


awk -v n=6 '{for (i=1; i<=NF; i++) if (length($i) == n) print $i}' file

or, with tr

tr ' ' '\n' file | awk -v n=6 'length($0)==n'
share|improve this answer
Or just use NF, you don't need to iterate to find the number of fields. – Chris Down Dec 11 '12 at 16:24
Sorry @ChrisDown, I don't understand your comment. Use NF where? – glenn jackman Dec 11 '12 at 16:56
Oh, apologies, I misunderstood the intent of the question (misread as 6 fields rather than six characters in a field). – Chris Down Dec 11 '12 at 17:02

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.