Count line lengths in file using command line tools

Pete Hamilton picture Pete Hamilton · May 25, 2013 · Viewed 59.7k times · Source

Problem

If I have a long file with lots of lines of varying lengths, how can I count the occurrences of each line length?

Example:

file.txt

this
is
a
sample
file
with
several
lines
of
varying
length

Running count_line_lengths file.txt would give:

Length Occurences
1      1
2      2
4      3
5      1
6      2
7      2

Ideas?

Answer

Ignacio Vazquez-Abrams picture Ignacio Vazquez-Abrams · May 25, 2013

count.awk:

{
  print length($0);
}

...

$ awk -f count.awk input.txt | sort | uniq -c
      1 1
      2 2
      3 4
      1 5
      2 6
      2 7