How to Count Lines in a File Using wc in Linux

In a graphical text editor like Microsoft Word, finding the word count or line count of a document usually involves looking at the bottom status bar. On a headless Linux server, you do not have that luxury. When you are writing a bash script, analyzing a massive server error log, or processing a CSV file containing user data, you frequently need to know exactly how much data you are dealing with before you begin processing it. The wc (Word Count) command is a simple, highly optimized utility designed to instantly provide this metric.

Understanding the ‘wc’ Command

Despite its name, the Word Count command does more than just count words. By default, it analyzes a file and outputs three distinct numbers: the number of lines, the number of words, and the number of bytes (characters). However, system administrators almost always use specific “flags” to force wc to report only one specific metric to avoid cluttering the terminal output.

Step-by-Step: Counting Lines

The most common use case for wc is counting lines, which is invaluable for determining how many records exist in a database dump or how many errors occurred in a log file.

  1. Open your terminal.
  2. To count the lines in a specific file, you will use the -l (Line) flag.
  3. Type the command:
    wc -l filename.txt
  4. Press Enter.

The output will be extremely concise, printing a single number followed by the filename (e.g., 1452 filename.txt). This tells you there are exactly 1,452 lines in the document.

Using wc with Other Commands (Piping)

The true power of wc emerges when you combine it with other Linux commands using a “pipe” (|). A pipe takes the output of the first command and feeds it directly into wc to be counted, rather than printing it to the screen.

Example 1: How many files are in this directory?
Instead of manually counting a long list of files, you can use the ls (list) command and pipe it to wc.

  • Type: ls -1 | wc -l
  • Explanation: ls -1 lists every file on a single vertical line. The pipe sends that vertical list to wc -l, which counts the lines. The output will be a single number representing the total file count.

Example 2: How many times did a specific error occur?
If you are searching a massive server log for the word “FAILED”, you can use the grep command to extract the errors, and wc to count them.

  • Type: grep "FAILED" server_log.txt | wc -l
  • Explanation: grep isolates every line containing the word “FAILED”. wc -l counts those isolated lines. You instantly know exactly how many failures occurred without reading the log yourself.

By mastering the wc -l command and understanding how to pipe data into it, you gain the ability to rapidly quantify massive amounts of system information.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.