CIS120Linux Fundementals
The head, tail and wc Commands
The head
, tail
, and wc
commands in Linux are fundamental tools for handling text files and streams. Each command serves a specific purpose, allowing users to view and analyze file content efficiently.
The head Command
The head
command is used to display the beginning of a file. By default, it shows the first ten lines, but you can specify the number of lines to display. The basic syntax is:
head [OPTION]... [FILE]...
Common Options for head
Option | Description |
---|---|
-n |
Print the first NUM lines |
-c |
Print the first NUM bytes |
-q |
Never print headers |
-v |
Always print headers |
For example, to display the first 5 lines of a file, use:
head -n 5 filename.txt
To display the first 20 bytes of a file, use:
head -c 20 filename.txt
The tail Command
The tail
command is used to display the end of a file. Like head
, it shows the last ten lines by default but can be customized to show a specific number of lines or bytes. The basic syntax is:
tail [OPTION]... [FILE]...
Common Options for tail
Option | Description |
---|---|
-n |
Print the last NUM lines |
-c |
Print the last NUM bytes |
-f |
Output appended data as the file grows (useful for logs) |
-q |
Never print headers |
-v |
Always print headers |
For example, to display the last 10 lines of a file, use:
tail -n 10 filename.txt
To follow a file and display new lines as they are added (useful for monitoring log files), use:
tail -f filename.txt
The wc Command
The wc
(word count) command is used to count the number of lines, words, and bytes in a file. It provides a quick way to get an overview of a file's size. The basic syntax is:
wc [OPTION]... [FILE]...
Common Options for wc
Option | Description |
---|---|
-l |
Print the newline counts |
-w |
Print the word counts |
-c |
Print the byte counts |
-m |
Print the character counts |
-L |
Print the length of the longest line |
For example, to count the number of lines in a file, use:
wc -l filename.txt
To count the number of words in a file, use:
wc -w filename.txt
To count the number of bytes in a file, use:
wc -c filename.txt
Examples
Displaying the first 10 lines of a file:
head filename.txt
Displaying the last 15 lines of a file:
tail -n 15 filename.txt
Counting the number of lines, words, and bytes in a file:
wc filename.txt
Counting the number of characters in a file:
wc -m filename.txt
Summary
The head
, tail
, and wc
commands are essential for viewing and analyzing file contents in Linux. The head
command allows you to view the beginning of a file, while the tail
command lets you see the end. The wc
command provides counts of lines, words, characters, and bytes, offering a quick way to understand the size and structure of a file. Mastering these commands will enhance your ability to manage and analyze text files efficiently in a Linux environment.