Counting files and their contents with wc

One of UNIX's handiest capabilities lets you count files and their contents. For example, you can count the number of files in a directory, or you can count the number of words or lines in a file. You do this counting with the wc command, as shown in Code Listing 6.1.

To count words using wc:

  • wc -w honeydo

    At the shell prompt, type wc -w (for words) and the name of the file you want to count the words in. wc will oblige, as shown in Code Listing 6.1.

To count lines with wc:

  • wc -l honeydo

    Use wc -l followed by the file name to count the lines in the file (Code Listing 6.2). This is useful for poetry or for things like lists (e.g., our "honey-do" list always has a minimum of 73 items on it).

Tip

You can find out how many files you have in a directory by using ls | wc -l to count the regular files, or ls -A | wc -l -2 to count all files and directories (except for the . and .. directories).


Tip

You can also find out how many bytes a specific file takes up using wc -b. Or, you can use wc with no flags at all to get the lines, words, and bytes.


Code Listing 6.1. Use wc -w to count the words in a file. The "honey-do" list in this example is quite a way from being the length of a novel.
[ejr@hobbes manipulate]$ wc -w honeydo
    235 honeydo

Code Listing 6.2. With 85 separate items in the list, however, it's plenty long enough.
[ejr@hobbes manipulate]$ wc -l honeydo
    85 honeydo

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.207.129