head Command ExamplesThe head command in Linux displays the first few lines of a file, by default the first 10 lines. It is useful for quickly inspecting the beginning of text files. Below are 10 examples demonstrating various uses of the head command with detailed explanations.
head file.txt
Displays the first 10 lines of file.txt. This is the default behavior of the head command.
Sample Output: (Assuming file.txt contains a list of names)
Alice
Bob
Charlie
David
Eve
Frank
Grace
Hannah
Ian
Jack
head -n 5 file.txt
Displays the first 5 lines of file.txt using the -n option to specify the number of lines.
Sample Output:
Alice
Bob
Charlie
David
Eve
head -c 20 file.txt
Displays the first 20 bytes of file.txt using the -c option. This includes newlines and other characters.
Sample Output: (Assuming each line is short and includes newlines)
Alice
Bob
Charli
head file1.txt file2.txt
Displays the first 10 lines of both file1.txt and file2.txt, with a header indicating each file.
Sample Output:
==> file1.txt <==
Alice
Bob
Charlie
David
Eve
Frank
Grace
Hannah
Ian
Jack
==< file2.txt >==
Apple
Banana
Cherry
Date
Fig
Grape
Kiwi
Lemon
Mango
Orange
head -q file1.txt file2.txt
Displays the first 10 lines of each file without the headers (e.g., ==> file1.txt <==) using the -q (quiet) option.
Sample Output:
Alice
Bob
Charlie
David
Eve
Frank
Grace
Hannah
Ian
Jack
Apple
Banana
Cherry
Date
Fig
Grape
Kiwi
Lemon
Mango
Orange
ls -l | head
Pipes the output of ls -l (detailed directory listing) to head, displaying the first 10 lines of the listing.
Sample Output:
total 12
-rw-r--r-- 1 user user 123 Oct 16 09:00 file1.txt
-rw-r--r-- 1 user user 456 Oct 16 09:00 file2.txt
-rw-r--r-- 1 user user 789 Oct 16 09:00 file3.txt
drwxr-xr-x 2 user user 4096 Oct 16 09:00 docs
head -n 5 file.txt | nl
Displays the first 5 lines of file.txt and pipes the output to nl to add line numbers.
Sample Output:
1 Alice
2 Bob
3 Charlie
4 David
5 Eve
head -v file1.txt file2.txt
Explicitly includes file headers for each file using the -v (verbose) option, even if it’s the default behavior on some systems.
Sample Output: Same as Example 4, with headers explicitly ensured.
head -n -3 file.txt
Displays all lines of file.txt except the last 3 lines. The -n -3 option removes the specified number of lines from the end.
Sample Output: (Assuming file.txt has 10 lines)
Alice
Bob
Charlie
David
Eve
Frank
Grace
head -n 5 file.txt | grep "Alice"
Displays the first 5 lines of file.txt and pipes the output to grep to filter lines containing "Alice".
Sample Output:
Alice
Note: The head command is ideal for quickly viewing the start of files or command outputs. For large files or specific use cases, combine it with other commands like grep, nl, or less. Check the man page (man head) for additional options and details specific to your system.