head
Overview
The head command displays the first lines of files or input streams. By default, it shows the first 10 lines, making it useful for previewing file contents.
Syntax
head [options] [file...]Common Options
| Option | Description |
|---|---|
-n num |
Show first num lines |
-c num |
Show first num bytes |
-q |
Suppress headers |
-v |
Always show headers |
-z |
Line delimiter is NUL |
--lines=num |
Same as -n |
--bytes=num |
Same as -c |
Key Use Cases
- Preview file contents
- Extract file headers
- Sample data examination
- Log file monitoring
- Quick file inspection
Examples with Explanations
Example 1: Default Usage
head file.txtShows first 10 lines of file
Example 2: Specific Line Count
head -n 5 file.txtShows first 5 lines
Example 3: Multiple Files
head -n 3 *.txtShows first 3 lines of each txt file
Example 4: Byte Count
head -c 100 file.txtShows first 100 bytes
Common Usage Patterns
Quick file preview:
head -20 logfile.logCSV header inspection:
head -1 data.csvCombined with tail:
head -50 file.txt | tail -10
Advanced Usage
Suppress filename headers:
head -q file1.txt file2.txtAlways show headers:
head -v file.txtProcess substitution:
head -5 <(command)
Performance Analysis
- Very fast for small line counts
- Efficient streaming operation
- Minimal memory usage
- Good for large files
- Stops reading after required lines
Best Practices
- Use appropriate line counts
- Combine with other text tools
- Consider byte vs line counting
- Use for quick file validation
- Helpful for debugging scripts
Integration Examples
Log analysis:
head -100 /var/log/syslog | grep errorData sampling:
head -1000 large_dataset.csv > sample.csvScript debugging:
head -5 "$input_file" | while read line; do echo "Processing: $line" done
Scripting Applications
File validation:
if head -1 "$file" | grep -q "^#"; then echo "File has header" fiQuick content check:
head -n 1 *.conf | grep -v "^#"