Counting Files and Their Contents with wc


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.

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 

To count words using wc:

  • wc -w honeydo

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

To count lines with wc:

  • wc -l honeydo

    Use wc -l followed by the filename 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).

Tips

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

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





Unix(c) Visual Quickstart Guide
UNIX, Third Edition
ISBN: 0321442458
EAN: 2147483647
Year: 2006
Pages: 251

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net