head - macOS


Overview

The head command in macOS is used to display the first few lines of text files to the standard output. It’s primarily useful for quickly reviewing or inspecting the beginning of files without opening the entire content. This command is particularly effective in scripting and data processing for previewing data or logs.

Syntax

The basic syntax of the head command is:

head [OPTIONS] [FILE]

If no FILE is specified or if the FILE is -, head reads from standard input.

Options/Flags

  • -n <num> or --lines=<num>: Specify the number of lines to display from the beginning of each file. Default is 10.

    Example:

    head -n 5 filename.txt
    
  • -c <num> or --bytes=<num>: Display the first bytes of each file instead of lines.

  • -q or --quiet: Suppress the headers that are normally printed with multiple files.

  • -v or --verbose: Always print headers with file names.

  • --help: Display a help message and exit.

  • --version: Show version information and exit.

Examples

  1. Display the first 10 lines of a file (default behavior):

    head filename.txt
    
  2. Display the first 20 lines of multiple files:

    head -n 20 file1.txt file2.txt
    
  3. Show the first 30 bytes of a file:

    head -c 30 filename.txt
    
  4. Use with no headers for several files:

    head -q -n 5 file1.txt file2.txt
    

Common Issues

  • Too many arguments: Ensure you are not exceeding the shell’s limits on the number of arguments or file size.

  • Non-existent files: head will throw an error if a specified file does not exist. Always check file path accuracy.

  • Binary files: Using head on binary files might cause unpredictable terminal behavior, such as changing control settings or character encodings.

Integration

Combine head with other commands to facilitate more complex tasks:

  1. Pipe head into grep for searching specific terms in the first few lines:

    head -n 50 file.log | grep "Error"
    
  2. Merge with sort and uniq for data analysis:

    head -n 100 datafile.csv | sort | uniq
    
  • tail – Displays the last part of files.
  • cat – Concatenates and displays files.
  • less – Allows backward and forward navigation through the file.
  • more – Similar to less, used to view the contents of a file one page at a time.

For more information, refer to the official macOS documentation or use the man head command to view the manual page.