cat displays file contents in Terminal. The name comes from "concatenate" - it can also combine multiple files.
View a File
cat filename.txt
Prints the entire file to your screen.
View Multiple Files
cat file1.txt file2.txt
Shows both files, one after another.
Show Line Numbers (-n)
cat -n filename.txt
Output:
1 First line
2 Second line
3 Third line
Show Non-Blank Line Numbers (-b)
cat -b filename.txt
Only numbers lines that have content.
Show Hidden Characters
cat -A filename.txt
Shows tabs as ^I and line endings as \$. Useful for debugging whitespace issues.
Or just show ends:
cat -e filename.txt
Concatenate Files
Combine files into a new file:
cat part1.txt part2.txt part3.txt > combined.txt
The > redirects output to a new file.
Append to a File
Add content to the end of a file:
cat newcontent.txt >> existing.txt
The >> appends instead of overwriting.
Create a Simple File
Type directly into a file:
cat > newfile.txt
Type your content, then press Control + D to save and exit.
Or with a heredoc:
cat > newfile.txt << 'EOF'
Line one
Line two
Line three
EOF
Better Alternatives for Long Files
cat dumps everything at once. For long files, use:
| Command | Purpose |
|---|---|
less filename |
Scroll through file |
head filename |
First 10 lines |
tail filename |
Last 10 lines |
head -n 50 filename |
First 50 lines |
Quick File Peek
# First 10 lines
head filename.txt
# Last 10 lines
tail filename.txt
# First 20 lines
head -n 20 filename.txt
Common Uses
Check a config file:
cat ~/.zshrc
View a log:
cat /var/log/system.log
Combine CSV files:
cat *.csv > all_data.csv
Create a simple script:
cat > script.sh << 'EOF'
#!/bin/bash
echo "Hello World"
EOF
chmod +x script.sh
Useless Use of Cat
Sometimes cat is unnecessary:
# Don't do this
cat file.txt | grep "pattern"
# Do this instead
grep "pattern" file.txt
Both work, but the second is cleaner and faster.
Copy File Contents to Clipboard
cat filename.txt | pbcopy
Now you can paste the contents elsewhere.
Reverse a File
Show lines in reverse order:
tail -r filename.txt
Or on some systems:
tac filename.txt
(Note: tac isn't installed by default on Mac)
Quick Reference
| Command | Result |
|---|---|
cat file.txt |
Display file |
cat -n file.txt |
Display with line numbers |
cat a.txt b.txt |
Display multiple files |
cat a.txt b.txt > c.txt |
Combine into new file |
cat new.txt >> old.txt |
Append to file |
cat > file.txt |
Create file interactively |
Keep Learning
cat is simple but essential. The free course covers this and other file viewing commands.
Check it out at Mac Terminal for Humans.