Viewing file beginnings: Which command prints the first lines (top portion) of a file on UNIX/Linux by default?

Difficulty: Easy

Correct Answer: head

Explanation:


Introduction / Context:
When inspecting configuration files or logs, you may only need the beginning of the file to verify headers or initial entries. UNIX/Linux provides head to quickly view the top lines without loading the entire file into a pager.



Given Data / Assumptions:

  • You want the first lines of a file (default often 10 lines).
  • You are using standard POSIX utilities.
  • File can be large, so a quick preview is desirable.


Concept / Approach:
The head command reads from the start of a file and prints the first N lines. You can adjust N with -n N. It is fast and useful in pipelines. Other commands like more or less page through content interactively; grep filters by pattern, not position.



Step-by-Step Solution:

Preview first lines: head file.txtSpecify count: head -n 20 file.txtCombine with tail for middle slices: head -n 1000 file | tail -n 20Use in pipelines: gunzip -c huge.gz | head


Verification / Alternative check:
Compare with less file.txt and jump to the beginning; both show the same initial content. head is non-interactive and terminates immediately after printing the requested lines.



Why Other Options Are Wrong:
grep: searches for patterns anywhere, not just the beginning. more: pager for interactive viewing. cat: dumps entire file; no line limit. None of the above: incorrect because head is correct.



Common Pitfalls:
Confusing -n with byte options on some platforms (e.g., -c counts bytes). Forgetting that default is typically 10 lines, which may differ by implementation.



Final Answer:
head

Discussion & Comments

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