Counting Words

Counting words is an essential capability in shell scripts. There are many ways to do it, with the easiest being the wc command. Unfortunately, it displays only the number of characters, words, or lines. What about when you need to count the number of occurrences of a particular word in a file? The wc command falls short. In this section, you will solve this problem using the following commands:

  • tr

  • sort

  • uniq

The tr command (short for transliterate) changes all the characters in one set into characters in a second set, whereas the sort command sorts the lines in an input file. The uniq command (short for unique) prints all the unique lines in a file.

The text of this chapter, ch15.doc, is used as the input file for the examples in ...

Get Sams Teach Yourself Shell Programming in 24 Hours, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.