Master the head Command: Preview Your Linux Files

View the start of files with the head command!

What is the head Command?

Imagine a file as a book, and the head command as your quick glance at its opening pages. Type head file.txt to display the first 10 lines of file.txt. It’s perfect for previewing logs, CSVs, or scripts without loading the entire file.

Why head is Essential

Quick Previews

Check the start of files like logs or CSVs.

Data Analysis

Inspect headers or metadata in structured files.

Scripting Utility

Use in pipelines to extract initial lines.

Syntax and Options

The head command is straightforward:

head [options] file...
        

Key options:

  • -n: Specify number of lines (e.g., -n 5).
  • -c: Specify number of bytes (e.g., -c 100).
  • -q: Quiet mode, suppress file headers for multiple files.
  • -v: Verbose mode, show file headers.

Real-World Examples

1. View First 10 Lines

Type this:

head access.log
        

Displays the first 10 lines of access.log.

2. Custom Line Count

Show first 5 lines:

head -n 5 data.csv
        

Output: First 5 lines of data.csv.

3. View Bytes

Show first 100 bytes:

head -c 100 file.txt
        

Output: First 100 bytes of file.txt.

4. Multiple Files with Headers

View multiple files:

head -v file1.txt file2.txt
        

Output: First 10 lines of each with headers like ==> file1.txt <==.

5. Scripting with head

Extract header from CSV:

#!/bin/bash
head -n 1 data.csv > header.csv
echo "Header saved to header.csv"
        

Saves the first line to header.csv.

Advanced Usage

Elevate head with these techniques:

  • Dynamic Line Counts: Use variables, e.g., head -n $NUM_LINES file.txt.
  • Piping Output: Combine with grep, e.g., head -n 20 log.txt | grep "ERROR".
  • Byte Precision: Use -c for binary or partial text extraction.
  • Multiple Files: Use -q to suppress headers for cleaner output.

Example: Extract first 50 bytes from multiple files:

head -c 50 -q *.txt
        

Pro Tips

Quick CSV Checks: Use head -n 1 to view headers.

Combine with Pipes: Use head in pipelines for filtered previews.

Alias Shortcut: Set alias h='head -n 5' for quick 5-line previews.

Common Mistakes to Avoid

Avoid these pitfalls with head:

  • Binary Files: Avoid head on binary files; use xxd or strings.
  • Incorrect Line Counts: Ensure -n uses a positive number.
  • Missing Files: Check file existence to avoid errors.

Explore More Linux Commands

Master Linux with our expert guides!