This article covers the basic syntax and usage of the Linux cat command. It explains how to use cat to display file contents, create and manipulate files, and combine multiple files. The article also addresses advanced display options and techniques for working with large files using cat.
Basic Syntax and Usage
Understanding the Cat Command Syntax
The cat command in Linux follows this syntax structure:
cat [OPTIONS] [FILE(S)]
Command Components
Component | Description |
---|---|
OPTIONS | Optional flags that modify the command's behavior (start with -) |
FILE(S) | One or more file names to work with |
Common Options
Option | Function |
---|---|
-n | Number all output lines |
-b | Number non-blank output lines |
-s | Suppress repeated empty output lines |
-E | Display $ at end of each line |
-T | Display TAB characters as ^I |
Usage Examples
Single File Example
cat -n file.txt
This displays the contents of file.txt with line numbers.
Multiple Files Example
cat file1.txt file2.txt file3.txt
This shows the contents of all three files in the order listed.
Standard Input
If no file is specified, cat waits for keyboard input. Press Ctrl+D to end input.
Combining Options
You can use multiple options together. For example:
cat -ns file.txt
This numbers non-blank lines and suppresses repeated empty lines in file.txt.
Tip: Use cat for quick file creation
You can use the cat command to create small files quickly. Here's how:
cat > newfile.txt
Enter your text here
Press Ctrl+D when done
This creates a new file named newfile.txt with the content you type.
Displaying File Contents
Viewing Single File Contents
Command | Description |
---|---|
cat filename |
Display contents of a single file |
cat -n filename |
Display contents with line numbers |
cat -v filename |
Display non-printing characters |
Example:
cat example.txt
Tip: Reverse File Contents
Use tac
instead of cat
to display file contents in reverse order:
tac example.txt
Displaying Multiple File Contents
Command | Description |
---|---|
cat file1.txt file2.txt file3.txt |
Display contents of multiple files in sequence |
cat -n file1.txt file2.txt file3.txt |
Display contents of multiple files with line numbers |
cat *.txt |
Display contents of all .txt files in current directory |
File Creation and Manipulation
Creating New Files with Cat
The cat command can create new files and add content to them in one step. Here's how to do it:
Operation | Command | Description |
---|---|---|
Create and add content | cat > newfile.txt |
Type content, press Ctrl+D to save and exit |
Create with multiple lines | cat << EOF > multiline.txt |
Use EOF to mark start and end of content |
Create an empty file | cat > emptyfile.txt < /dev/null |
Creates an empty file |
Tip: Use cat with redirection for quick file creation
When you need to create a file with a simple one-line content quickly, use cat with redirection:
echo "This is a quick file" | cat > quickfile.txt
This creates a file named quickfile.txt with the content "This is a quick file" in one command.
Appending Content to Existing Files
To add content to the end of existing files, use the >> operator:
Operation | Command | Description |
---|---|---|
Append content | cat >> existingfile.txt |
Type content, press Ctrl+D to save and exit |
Append from another file | cat sourcefile.txt >> destinationfile.txt |
Adds content from sourcefile to destinationfile |
Append multiple files | cat file1.txt file2.txt >> combinedfile.txt |
Adds content from file1 and file2 to combinedfile |
Append with here-document | cat << EOF >> existingfile.txt |
Use EOF to mark start and end of content |
Key Points
- Use
>
to create or overwrite a file - Use
>>
to append to an existing file without erasing its current content
File Concatenation
Combining Multiple Files
The cat command can merge the contents of multiple files into a single file. This process is called concatenation. Here's how to do it:
Operation | Command | Description |
---|---|---|
Combine files | cat file1.txt file2.txt > combined.txt |
Merges file1.txt and file2.txt into combined.txt |
Combine all text files | cat *.txt > allfiles.txt |
Merges all .txt files in the current directory into allfiles.txt |
Append to existing file | cat file3.txt >> combined.txt |
Adds content of file3.txt to the end of combined.txt |
Tip: Use sort with cat for organized concatenation
To combine files and sort the content alphabetically:
cat file1.txt file2.txt | sort > sorted_combined.txt
This merges file1.txt and file2.txt, sorts the content, and saves it in sorted_combined.txt.
Example: Combining log files
To merge multiple log files into a single, chronologically ordered file:
cat log1.txt log2.txt log3.txt | sort -n > combined_logs.txt
This combines log1.txt, log2.txt, and log3.txt, sorts them numerically (assuming timestamps are present), and saves the result in combined_logs.txt.
Copying File Contents
The cat command can also copy the contents of one file to another. Here's how:
Operation | Command | Description |
---|---|---|
Copy file content | cat source.txt > destination.txt |
Copies content from source.txt to destination.txt |
Copy and append | cat source.txt >> destination.txt |
Adds content from source.txt to the end of destination.txt |
Copy multiple files | cat file1.txt file2.txt > newfile.txt |
Copies content from file1.txt and file2.txt to newfile.txt |
Key Points
- Use
>
to create a new file or overwrite an existing one - Use
>>
to append to an existing file without erasing its current content - When combining files, the order of files in the command determines the order of content in the output file
- Be careful when using
>
as it will overwrite the destination file without warning
Advanced Display Options
Displaying Line Numbers
The cat command provides options to add line numbers to file contents, helping with line referencing and text structure analysis.
Option | Command | Description |
---|---|---|
-n | cat -n file.txt |
Numbers all lines, including blank lines |
-b | cat -b file.txt |
Numbers only non-blank lines |
Examples:
-
Number all lines:
cat -n example.txt
-
Number only non-blank lines:
cat -b example.txt
Tip: Using Line Numbers for Debugging
When debugging scripts or log files, use the -n option to add line numbers. This makes it easier to pinpoint specific lines when discussing issues with colleagues or in bug reports.
Combining Numbering with Other Options
You can use line numbering with other options:
cat -ns example.txt
This numbers non-blank lines and suppresses repeated empty lines.
Showing Non-Printing Characters
Cat can reveal non-printing characters, useful for debugging or analyzing file formatting.
Option | Command | Description |
---|---|---|
-v | cat -v file.txt |
Shows non-printing characters using ^ and M- notation |
-T | cat -T file.txt |
Displays TAB characters as ^I |
-E | cat -E file.txt |
Shows end-of-line $ character |
-A | cat -A file.txt |
Equivalent to -vTE, shows all non-printing characters |
Examples:
-
Display TAB characters:
cat -T script.sh
-
Show end-of-line markers:
cat -E config.txt
-
Reveal all non-printing characters:
cat -A document.txt ``
Here's the expanded information organized in tables and using Mermaid.js diagrams where possible, formatted in markdown:
File Content Formatting
Suppressing Empty Lines
The cat command can remove repeated empty lines from the output, making the content more compact and easier to read.
To suppress repeated empty lines, use the -s option:
cat -s filename.txt
This command will display the file content with only one blank line between paragraphs or sections, regardless of how many empty lines are in the original file.
Example | Command |
---|---|
Suppress empty lines in a single file | cat -s log.txt |
Combine multiple files and suppress empty lines | cat -s file1.txt file2.txt > combined.txt |
Tip: Cleaning up log files
Use the -s option when viewing log files to reduce clutter:
cat -s /var/log/syslog | less
This makes it easier to scan through log entries by removing excessive blank lines.
Reversing File Contents
To display file contents in reverse order (last line first), use the tac command, which is cat spelled backward:
tac filename.txt
The tac command reads the file from bottom to top and outputs each line in reverse order.
Example | Command |
---|---|
Reverse the content of a single file | tac names.txt |
Reverse and combine multiple files | tac file1.txt file2.txt > reversed_combined.txt |
Reverse a file and number the lines | tac file.txt | cat -n |
Tip: Analyzing log files in reverse chronological order
When troubleshooting recent issues in log files, use tac to view the most recent entries first:
tac /var/log/auth.log | less
This displays the latest log entries at the top, making it easier to find recent events.
Example: Reversing a CSV file's rows
If you have a CSV file with headers and want to reverse the order of data rows while keeping the header at the top, you can use a combination of head, tail, and tac:
(head -n 1 data.csv && tail -n +2 data.csv | tac) > reversed_data.csv
This command keeps the header row intact while reversing the order of all other rows in the CSV file.
Working with Large Files
Using Cat with More and Less Commands
Cat with More
cat largefile.txt | more
Key | Function |
---|---|
Space | Move forward one screen |
Enter | Move forward one line |
b | Move backward one screen |
q | Quit and return to the command prompt |
Cat with Less
cat largefile.txt | less
Key | Function |
---|---|
Space or f | Move forward one screen |
b | Move backward one screen |
g | Go to the beginning of the file |
G | Go to the end of the file |
/pattern | Search forward for a pattern |
?pattern | Search backward for a pattern |
n | Repeat the last search |
q | Quit and return to the command prompt |
Tip: Using less for log file analysis
When analyzing large log files, use less with cat:
cat /var/log/syslog | less
This allows you to search for specific patterns and navigate easily through the log file.
Viewing Multiple Large Files
To view multiple large files sequentially:
cat file1.txt file2.txt file3.txt | less
Displaying with Line Numbers
To display large files with line numbers:
cat -n largefile.txt | less
Example: Combining cat with grep for efficient searching
To search for a specific pattern in a large file and display the results with line numbers:
cat largefile.txt | grep -n "search_pattern" | less
This command combines cat, grep, and less to efficiently search and display results from a large file.
File Content Conversion
Binary and Hexadecimal Conversion
The cat command, combined with other Linux utilities, can convert file contents to binary and hexadecimal formats. This is useful for analyzing file structures, debugging, or working with low-level data.
Converting to Binary Format
To convert file contents to binary format, use cat with the xxd command:
cat file.txt | xxd -b
This command displays the file content in binary format, showing both the binary representation and the ASCII characters.
Option | Description |
---|---|
-b | Output in binary instead of hex |
Example output:
00000000: 01001000 01100101 01101100 01101100 01101111 Hello
00000005: 00100000 01010111 01101111 01110010 01101100 Worl
0000000a: 01100100 00001010 d.
Converting to Hexadecimal Format
To convert file contents to hexadecimal format, use cat with xxd without any options:
cat file.txt | xxd
This command displays the file content in hexadecimal format, showing both the hex values and the ASCII characters.
Example output:
00000000: 4865 6c6c 6f20 576f 726c 640a Hello World.
For a more compact hexadecimal view, you can use the hexdump command:
cat file.txt | hexdump -C
Option | Description |
---|---|
-C | Display output in canonical hex+ASCII format |
Example output:
00000000 48 65 6c 6c 6f 20 57 6f 72 6c 64 0a |Hello World.|
0000000c
Tip: Using hexdump for file comparison
When comparing binary files, use hexdump to get a human-readable representation:
cat file1.bin | hexdump -C > file1.hex
cat file2.bin | hexdump -C > file2.hex
diff file1.hex file2.hex
This method helps identify differences between binary files more easily.
Example: Analyzing file headers
To examine the header of a PNG image file:
cat image.png | xxd -l 32
This command displays the first 32 bytes of the PNG file in hexadecimal format, which includes the file signature and critical chunks.
These conversion methods are valuable for users who need to analyze file structures, debug binary data, or work with low-level file formats. They provide different ways to view file contents beyond the standard text representation, offering insights into the underlying data structure of files.
Selective Content Display
Displaying Specific Lines
The cat command, combined with other utilities, can display specific lines or portions of file contents. This is useful for focusing on particular sections of a file without viewing the entire content.
To display specific lines, you can use cat with the sed or awk commands:
Operation | Command | Description |
---|---|---|
Display a single line | cat file.txt | sed -n '5p' |
Shows only line 5 of the file |
Display a range of lines | cat file.txt | sed -n '10,15p' |
Shows lines 10 to 15 of the file |
Display lines matching a pattern | cat file.txt | grep "pattern" |
Shows lines containing the specified pattern |
Display the first n lines | cat file.txt | head -n 10 |
Shows the first 10 lines of the file |
Display the last n lines | cat file.txt | tail -n 5 |
Shows the last 5 lines of the file |
Tip: Combining Commands for Advanced Filtering
You can combine multiple commands to create more complex filters:
cat file.txt | grep "important" | sed -n '1,5p'
This command first finds lines containing "important", then displays only the first 5 of those lines.
Sorting File Contents
Cat can be used with the sort command to alphabetically or numerically sort file contents. This helps organize data or find specific entries in large files.
Operation | Command | Description |
---|---|---|
Sort alphabetically | cat file.txt | sort |
Sorts lines alphabetically |
Sort numerically | cat file.txt | sort -n |
Sorts lines numerically |
Sort in reverse order | cat file.txt | sort -r |
Sorts lines in reverse order |
Sort and remove duplicates | cat file.txt | sort -u |
Sorts lines and removes duplicates |
These techniques allow users to extract and organize specific information from files, making data analysis and file management tasks more manageable.
System Information Retrieval
Viewing CPU Information
The cat command displays system CPU details by reading files in the /proc filesystem. This virtual filesystem provides an interface to kernel data structures, allowing access to real-time system information.
To view CPU information:
cat /proc/cpuinfo
This command shows detailed information about the system's CPU(s):
Information | Description |
---|---|
processor | CPU number starting from 0 |
vendor_id | CPU manufacturer |
model name | CPU model and family |
cpu MHz | Current clock speed |
cache size | L2 cache size |
cores | Number of cores per CPU |
Tip: Filtering CPU Information
To display specific CPU information, combine cat with grep:
cat /proc/cpuinfo | grep "model name"
This shows only the model name of your CPU(s).
For a summary of CPU cores:
cat /proc/cpuinfo | grep "cpu cores" | uniq
To view the total number of processors:
cat /proc/cpuinfo | grep "physical id" | sort | uniq | wc -l
Example: Checking CPU Temperature
On systems with lm-sensors installed, use cat to check CPU temperature:
cat /sys/class/thermal/thermal_zone*/temp
Note: The output is in millidegrees Celsius. Divide by 1000 for Celsius.
Using cat to view system information provides a quick way to access important hardware details without additional software. This can be useful for system administrators, developers, and users who need to check system specifications or troubleshoot hardware-related issues.