Counting lines in a file on Unix/Linux Which single command counts only the number of lines contained in a text file (no words or bytes)?

Difficulty: Easy

Correct Answer: wc -l

Explanation:


Introduction / Context:
Simple text analytics are frequently needed on Unix-like systems. The wc (word count) utility quickly provides counts of lines, words, and bytes. Knowing the correct option flags avoids writing custom scripts for basic statistics.



Given Data / Assumptions:

  • The input is a regular text file or piped text stream.
  • We need the number of lines only.
  • We are using a standard POSIX wc implementation.


Concept / Approach:

wc supports independent flags for each metric: -l for lines, -w for words, and -c for bytes. Combining flags prints multiple counts in order. To get lines alone, specify -l by itself.



Step-by-Step Solution:

Choose the correct metric: lines.Run wc -l filename to print the line count and filename.For just the number, you can use command substitution or cut (e.g., wc -l < filename).With pipelines, use ... | wc -l to count lines in a stream.


Verification / Alternative check:

Cross-check with nl -ba filename | tail -n 1, which numbers all lines. The final number should equal the output from wc -l.



Why Other Options Are Wrong:

  • wc -c: counts bytes.
  • wc -w: counts words.
  • wc -r: not a standard option.
  • None of the above: incorrect because wc -l is correct.


Common Pitfalls:

Counting lines in files without a trailing newline can yield off-by-one expectations; remember wc -l counts newline characters. On huge files, prefer wc for performance over scripting loops.


Final Answer:

wc -l

More Questions from Unix

Discussion & Comments

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