How to Print First 10 Lines of Files in Linux

The head command, especially when combined with other commands through pipes, becomes an essential tool for quick file inspection and data analysis in Linux environments.

Alby Andersen

The head command in Linux is a simple but powerful utility used to display the beginning portion of files. By default, it outputs the first 10 lines of a file, though this number can be easily customized. This command is particularly useful when you want to quickly preview the contents of large files, check file headers, or view the beginning of log files without opening the entire document.

Display the First 10 Lines of a File

head file.txt


Shows the default first 10 lines of file.txt.


Show a Specific Number of Lines

head -n 5 file.txt


Displays the first 5 lines of file.txt.


View the Beginning of Multiple Files

head file1.txt file2.log


Shows the first 10 lines of both files, with headers indicating each file name.


Display Bytes Instead of Lines

head -c 100 file.txt


Outputs the first 100 bytes of the file (useful for binary or fixed-size data).


Combine with tail to Extract a Middle Section

head -20 file.txt | tail -10
  • Gets lines 11–20 of file.txt (first 20 lines via head, then last 10 via tail).

Suppress File Headers in Output

head -q file1.txt file2.txt


Hides filenames when viewing multiple files (-q = quiet mode).


Always Show Filename Headers

head -v file.txt


Forces the filename header, even for a single file (-v = verbose).


Pipe Output from Another Command

ls -l /var/log | head -n 3


Lists files in /var/log and shows the first 3 entries.


Redirect Output to a New File

head -n 5 file.txt > top_lines.txt


Saves the first 5 lines of file.txt into top_lines.txt.


Monitor Real-Time Logs (Partial Preview)

tail -f access.log | head -n 20


Note: This isn’t truly real-time but captures the first 20 lines of the streaming log.


Key Notes:

  • Default Behavior: head shows the first 10 lines if no options are specified.
  • Large Files: Safe for massive files (e.g., logs) since it doesn’t load the entire file.
  • Binary Files: Use -c to preview bytes, but avoid text operations on binaries.
Share This Article