cat is one of the most commonly used and fundamental commands in Linux systems, primarily used to view, concatenate, and output file contents. It can output file contents to the terminal (screen) or redirect them to other files or commands.
๐ Command Format:
cat [options] [filenames...]
๐งพ Common Options:
| Option | Description |
|---|---|
-n |
Display line numbers (including empty lines) |
-b |
Display line numbers, but ignore empty lines |
-E |
Display a $ symbol at the end of each line |
-T |
Display Tabs as ^I |
-v |
Show non-printing characters (except for newline and Tab) |
-s |
Suppress repeated empty lines to a single empty line |
--help |
Display help information |
--version |
Show the version information of cat |
๐ก Example Usage:
Example 1: View File Contents
cat filename.txt
Outputs the entire content of
filename.txtto the terminal.
Example 2: Display Line Numbers (Including Empty Lines)
cat -n filename.txt
Example 3: Display Line Numbers (Excluding Empty Lines)
cat -b filename.txt
Example 4: Show End-of-Line Symbol $
cat -E filename.txt
Example 5: Concatenate Multiple Files and Output to a New File
cat file1.txt file2.txt > combined.txt
Concatenates the contents of
file1.txtandfile2.txtand writes to a new filecombined.txt.
Example 6: Use Pipe to Pass cat Output to Other Commands
cat filename.txt | grep "keyword"
Finds lines in
filename.txtthat contain “keyword”.
Example 7: Create a File (Interactive)
cat > newfile.txt
After entering content, press
Ctrl+Dto save and exit.
Example 8: Append Content to a File
cat >> newfile.txt
Appends input content to the end of
newfile.txt.
โ ๏ธ Notes:
-
catis not suitable for viewing large files, as it outputs the entire content to the terminal at once. Consider usinglessormore:cat largefile.txt | less -
If the file does not exist,
catwill return an error:cat: filename.txt: No such file or directory
โ Summary of Use Cases:
| Purpose | Command |
|---|---|
| View file contents | cat filename |
| View and display line numbers | cat -n filename |
| Concatenate files | cat file1 file2 > merged |
| Create a file | cat > filename |
| Append content | cat >> filename |
| View non-printing characters | cat -A filename |