Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to display the first part of the file in the Linux system?
The head command in Linux is used to display the first part of a file or piped data. By default, it shows the first 10 lines of the specified file, making it useful for quickly previewing file contents without opening the entire file.
Syntax
The general syntax of the head command is −
head [OPTION]... [FILE]...
Common Options
| Option | Description |
|---|---|
| -n NUM | Display the first NUM lines instead of the default 10 |
| -c NUM | Display the first NUM bytes of each file |
| -q, --quiet | Never display headers with file names |
| -v, --verbose | Always display headers with file names |
| --help | Display help message and exit |
| --version | Show version information and exit |
Examples
Basic Usage
First, let's create a sample file with multiple lines −
$ cat > sample.txt First line Second line Third line Fourth line Fifth line Sixth line Seventh line Eighth line Ninth line Tenth line Eleventh line Twelfth line
Display the first 10 lines (default behavior) −
$ head sample.txt
First line Second line Third line Fourth line Fifth line Sixth line Seventh line Eighth line Ninth line Tenth line
Display Specific Number of Lines
To display the first 5 lines −
$ head -n 5 sample.txt
First line Second line Third line Fourth line Fifth line
Display First N Bytes
To display the first 20 bytes −
$ head -c 20 sample.txt
First line Second li
Display Lines Between Two Numbers
To display lines 3 to 6, combine head and tail commands −
$ head -n 6 sample.txt | tail -n 4
Third line Fourth line Fifth line Sixth line
Multiple Files
When processing multiple files, head displays headers by default −
$ head -n 3 file1.txt file2.txt
==> file1.txt <== Line 1 of file1 Line 2 of file1 Line 3 of file1 ==> file2.txt <== Line 1 of file2 Line 2 of file2 Line 3 of file2
Use -q option to suppress headers −
$ head -n 2 -q file1.txt file2.txt
Common Use Cases
Log file inspection − Quickly view the beginning of log files
Configuration preview − Check the start of configuration files
Data sampling − Preview the first few records of data files
Script debugging − View the beginning of script output
Conclusion
The head command is an essential Linux utility for viewing the beginning of files efficiently. Combined with other commands like tail, it provides powerful text processing capabilities for file analysis and system administration tasks.
