How to Count the Number of Lines in a File in Ubuntu Terminal

When managing an Ubuntu server, you will frequently deal with massive text files. A production web server might generate an error log containing tens of thousands of lines of data in a single day. A developer might hand you a CSV file containing hundreds of thousands of customer records.

If you want to know exactly how many errors occurred yesterday, or exactly how many customers are in the database, opening a 500-megabyte text file in a visual editor like Nano or Vim just to manually scroll to the bottom is incredibly inefficient, and will likely crash your terminal.

Linux provides a dedicated, lightning-fast utility designed specifically to count words and lines.

The ‘wc’ (Word Count) Command

The wc command is one of the oldest and most reliable utilities in the Linux ecosystem. To count the lines in a file, you must append the -l (lines) flag.

  1. Open your terminal or SSH into your Ubuntu server.
  2. Type the command, the flag, and the exact path to your file, then press Enter:
wc -l /var/log/apache2/error.log

The terminal will instantly output a single number followed by the filename. For example:

45218 /var/log/apache2/error.log

This instantly confirms that there are exactly 45,218 lines of text inside that specific file. The command operates in milliseconds, even on files that are multiple gigabytes in size.

Counting the Output of Another Command (Piping)

The true power of the wc command is that it doesn’t just read static files; it can count the output of other commands in real-time using a “pipe” (|).

For example, what if you only want to count how many times the specific word “Failed” appears in the log file, rather than counting every single line?

You can use the grep command to search for the word, and then pipe that filtered output directly into the wc command:

grep "Failed" /var/log/apache2/error.log | wc -l

In this scenario, grep pulls out only the lines containing the error, and hands them invisibly to wc. The terminal will then output a single, highly specific number (e.g., 142), instantly telling you exactly how many failures occurred, without you ever having to open or read the file yourself.

Get the best tech tips delivered straight to your inbox.

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