I have a file with a number of lines in a file filename
.
I want to count how many lines start with character 'a', with 'b' and so on in one go.
What command i should execute.?
I have a file with a number of lines in a file filename
.
I want to count how many lines start with character 'a', with 'b' and so on in one go.
What command i should execute.?
Not exactly sure I understand your question correctly, is this what you are looking for?
$ cat foo.input
afoo
abar
bfoo
bbar
bquux
cfoo
$ awk '{a[substr($0, 1, 1)]++}END{for (c in a)print c, a[c]}' foo.input
a 2
b 3
c 1
Another, simpler solution is to use colrm
and uniq
:
$ colrm 2 < foo.input | uniq -c
2 a
3 b
1 c
This is a perfect job for uniq
:
uniq -c -w 1 filename
-w 1
compares only the the first character of each line; -c
counts the occurrences.
With foo.input
from Adrian's answer you get (don't be confused about afoo
, bfoo
etc.; these are simply the first lines which start with a
, b
, etc.)
2 afoo
3 bfoo
1 cfoo
Pipe the result through sort -n
, if you want it sorted by the number of occurrences:
$ uniq -c -w 1 foo.input | sort -n
1 cfoo
2 afoo
3 bfoo
uniq
solution that gets rid of the confusing output).
Aug 30, 2013 at 9:17
Or, if you're more into use of perl and grep:
perl -le '$, = "\n"; print ("a".."z")' | xargs -i grep -c '^{}' foo.input
Another solution, because sometimes it's easier to remember small blocks and assemble them :
$ cat foo.input afoo abar bfoo bbar bquux cfoo $ cat foo.input | cut -c 1 | tr '[[:upper:]]' '[[:lower:]]' | sort | grep '^[a-z]'| uniq -c 2 a 3 b 1 c
Explanation of the one-liner :
cat
read the filecut -c 1
trims everything but the first character of each linetr '[[:upper:]]' '[[:lower:]]'
replaces uppercase to lowercasesort
... sorts the linesgrep '^[a-z]'
remove lines not beginning with a letteruniq -c
counts identical linescut -c 1 <foo.input
but that messed up with the <pre> formatting. Your alternative works indeed.
[[:upper:]]
/[[:lower:]]
, just in case.
Aug 30, 2013 at 9:25