Which command can you execute to count only the number of lines in a file on Unix/Linux?

Difficulty: Easy

Correct Answer: wc -l

Explanation:


Introduction / Context:
Counting lines is a frequent need when validating datasets, logs, or configuration files. Unix/Linux provides a compact utility that can report multiple metrics, and with the right switch it outputs exactly the line count, making it convenient for scripting and quick checks.


Given Data / Assumptions:

  • You have a text file and want the total number of lines.
  • Only standard POSIX tools are assumed.
  • Output format should be script-friendly if needed.


Concept / Approach:
The 'wc' (word count) utility prints lines, words, and bytes. By passing the '-l' option, 'wc' restricts output to the line count. You can supply one or more filenames; with multiple files, it prints per-file counts plus a total. In pipelines, 'wc -l' counts the number of input lines from standard input.


Step-by-Step Solution:

Count lines in file: wc -l filenameCount lines from a pipeline: grep ERROR app.log | wc -lSuppress filename in output: wc -l < filenameCount lines across multiple files: wc -l file1 file2


Verification / Alternative check:
Use 'awk 'END{print NR}' filename' or 'nl -ba filename | tail -n 1' to confirm the same count. For binary or huge files, ensure the input has newline-terminated records to avoid off-by-one expectations.


Why Other Options Are Wrong:

  • lc / cl / count: Not standard Unix commands.
  • None of the above: Incorrect because 'wc -l' is the exact tool for line counts.


Common Pitfalls:
Assuming bytes equal characters in multi-byte encodings (irrelevant for line counts) and forgetting input redirection when you do not want the filename echoed with the count.


Final Answer:
wc -l

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion