The cat
command in Linux (short for “concatenate”) is used to read, combine, and write file contents. It is one of the most versatile commands for viewing file content directly in the terminal, merging multiple files into one, creating new files, or redirecting output. While simple, it’s essential for tasks like debugging, scripting, and quick file operations.
Display a File’s Content
cat file.txt
Prints the entire content of file.txt
to the terminal.
View Multiple Files
cat file1.txt file2.txt
Displays the contents of file1.txt
and file2.txt
sequentially.
Create a New File
cat > newfile.txt
Creates newfile.txt
. Type input, then press Ctrl + D
to save and exit.
Append to a File
cat >> existing_file.txt
Adds text to the end of existing_file.txt
(press Ctrl + D
to finish).
Combine Files into One
cat file1.txt file2.txt > mergedfile.txt
Merges file1.txt
and file2.txt
into mergedfile.txt
.
Display Line Numbers
cat -n file.txt
Shows line numbers for all lines in file.txt
.
Show Non-Printable Characters
cat -v file.txt
Reveals non-printing characters (e.g., tabs as ^I
).
Concatenate with Pipes
cat file.txt | grep "keyword"
Searches for keyword
in file.txt
using grep
.
Reverse Output Order
tac file.txt
Prints lines in reverse order (uses tac
, the reverse of cat
).
Read Input Until a Delimiter
cat << EOF > output.txt
This is line 1.
This is line 2.
EOF
Creates output.txt
with lines typed between << EOF
and EOF
.
Display File with Pagination
cat longfile.txt | more
Shows longfile.txt
one screen at a time (use more
or less
).
Create a Backup of a File
cat original.txt > backup.txt
Copies the content of original.txt
to backup.txt
.
Append Multiple Files
cat file1.txt file2.txt >> combined.txt
Adds the content of file1.txt
and file2.txt
to combined.txt
.
View Files with Wildcards
cat *.log
Displays all .log
files in the current directory.
Remove Blank Lines
cat -s file.txt
Squeezes consecutive blank lines into a single blank line.
Highlight Line Endings
cat -E file.txt
Displays $
at the end of each line (helps to spot trailing spaces).
Create a Multi-Line File Quickly
cat > list.txt << EOF
Apple
Banana
Cherry
EOF
Creates list.txt
with three lines of fruit names.
Combine Binary Files
cat part1.bin part2.bin > full.bin
Merges binary files (e.g., split archives).
Key Notes:
- Large Files: Avoid
cat
for huge files—useless
ortail
instead. - Modifications:
cat
doesn’t edit files—it only reads or combines them. - Overwriting: Use
>
carefully, as it overwrites existing files. Use>>
to append.