Linux cat Command
The cat
command in Linux is used for displaying, combining, and creating text files. It's a versatile tool for viewing file contents, appending text, and redirecting output to other files.
Basic Syntax
Common Uses of cat
1. Viewing File Contents
Using cat
with a single file displays the entire content of the file to the terminal.
Command
Output
Explanation:
- This command displays the contents of
file.txt
in the terminal.
2. Displaying Multiple Files
You can display multiple files consecutively by specifying them in the command. This is useful for quickly reading through multiple files without opening each one.
Command
Output
Explanation:
cat file1.txt file2.txt
outputs the contents of bothfile1.txt
andfile2.txt
, showing them one after the other.
3. Creating a New File
You can use cat
with redirection (>
) to create a new file and add content to it.
Command
Input (type and press Ctrl+D
to save):
Output
Explanation:
cat > newfile.txt
lets you createnewfile.txt
. Whatever you type in the terminal is saved to the file when you pressCtrl+D
.
4. Appending Content to an Existing File
Using >>
allows appending additional content to the end of an existing file without overwriting it.
Command
Input (type and press Ctrl+D
to save):
Output in file.txt
Explanation:
cat >> file.txt
opensfile.txt
for appending. The additional content is added to the end when you pressCtrl+D
.
5. Displaying Line Numbers
The -n
option displays line numbers for each line of the file.
Command
Output
Explanation:
cat -n file.txt
adds line numbers to each line infile.txt
, making it useful for reviewing line-by-line content.
6. Merging Multiple Files into One
You can combine multiple files into a single file by redirecting the output of multiple files to a new one.
Command
Output in merged.txt
Explanation:
cat file1.txt file2.txt > merged.txt
combinesfile1.txt
andfile2.txt
and saves the result tomerged.txt
.
Summary of Common cat
Commands
Command | Description |
---|---|
cat file.txt | Displays the content of file.txt . |
cat file1.txt file2.txt | Displays the contents of multiple files. |
cat > newfile.txt | Creates a new file and lets you type its content. |
cat >> file.txt | Appends new content to the end of file.txt . |
cat -n file.txt | Displays content with line numbers. |
cat file1.txt file2.txt > merged.txt | Combines multiple files into one. |
The cat
command is quick and efficient for managing text file content, allowing users to display, create, append, and merge files easily.