Viewing the Beginning and Ending Lines of a File in Linux
When working with large text files in Linux, it can be useful to quickly view the beginning or ending lines of the file. The head and tail commands are perfect for this task.Using head to View the Beginning of a File
The head command is used to display the first few lines of a file. By default, it shows the first 10 lines, but you can specify a different number of lines if needed.Syntax:
head [OPTION]... [FILE]...
Example: To view the first 10 lines of a file named example.txt, you would use:
Code:
head example.txt
To view the first 20 lines, you can use the -n option:
Code:
head -n 20 example.txt
Using tail to View the Ending of a File
The tail command is used to display the last few lines of a file. Like head, it shows the last 10 lines by default, but this can be adjusted.Syntax:
tail [OPTION]... [FILE]...
Example: To view the last 10 lines of example.txt, you would use:
Code:
tail example.txt
To view the last 20 lines, use the -n option:
Code:
tail -n 20 example.txt
Combining head and tail to View the Middle of a File
You can combine head and tail to view a specific range of lines from the middle of a file. For example, to view lines 11 to 20 of example.txt, you can first use head to get the first 20 lines and then tail to get the last 10 lines of that output.Example:
Code:
head -n 20 example.txt | tail -n 10
This command sequence works as follows:
- head -n 20 example.txt extracts the first 20 lines of example.txt.
- tail -n 10 then extracts the last 10 lines from the output of the head command, effectively giving you lines 11 to 20 of the original file.
I hope this helps you understand how to use head and tail in Linux!