This tutorial explores the head command in Linux, a utility designed to display the initial lines of a text file. We will cover its basic usage and introduce various parameters for enhanced functionality.
① head Command
The head
command is used to view the beginning of a file, making it particularly useful for quickly inspecting the first few lines of a large text document.
Command Usage
Let’s start with a basic example. We have a file called example.txt
in the /home/labex/project
directory, and we want to display the first 10 lines of a file.
Input:
head /home/labex/project/example.txt
Output:
This is a sample text file to illustrate the head command.
Hello there! This file is meant to show how the head command works.
Imagine you have a list of your favorite fruits:
1. Apple
2. Banana
3. Orange
4. Grape
This command displays the initial 10 lines of the specified file (example.txt
). As with the less
tutorial, this initial stage will focus solely on the basic usage of the head
command.
② Parameters and Usage Examples
The head
command offers a variety of parameters to customize its behavior. We will introduce some of the most commonly used ones and provide usage examples in increasing order of complexity.
Option Parameter
head [option] file
-n N
: Display the first N lines of the file.-q
: Suppress headers when multiple files are specified.
Example Usage
1. Specify the Number of Lines to Display (-n
)
The -n
option with the head
command is used to specify the number of lines to display from the beginning of a file.
Input:
head -n 3 /home/labex/project/example.txt
In this example, head -n 3
displays the first three lines of the file.
Output:
This is a sample text file to illustrate the head command.
Hello there! This file is meant to show how the head command works.
2. Head with Character Count (-c)
The -c
option in the head
command is used to specify the number of characters to display from the beginning of a file.
Input:
head -c 50 /home/labex/project/example.txt
Output:
This is a sample text file to illustrate the head
In this example, head -c 50
displays the first 50 characters of the file.
③ Summary
To summarize, the head
command is a valuable tool for quickly inspecting the beginning of a text file. Whether you need to view a specific number of lines, bytes, or handle multiple files efficiently, head
offers a straightforward solution for initial file examination.
🙌 Thanks for reading this far — we genuinely hope that we can help you in the programming road by making the overall experience fun, fun and fun. You can practice this tutorial with auto-validation on LabEx 🚀
Practice Now: 📖 Linux head Command: File Beginning Display Learn More: 🌳 Linux Skill Tree
Want to contribute?
Here are few ways you can help.
- Becoming an instructor;
- Submitting your own tutorial;
- Or you can simply make your own proposal;
Join our Discord or tweet us @WeAreLabEx !