cat


cat (concatenate and display file content)

The cat command is a core utility used to read data from files and output their contents to standard output. While its name comes from "concatenate" (to link things together), its most frequent use is for quickly viewing the entire content of a file on the screen.


Example 1: Display the content of a single file

# Display the full content of the system's host configuration file
cat /etc/hosts

Explanation: This command reads the /etc/hosts file from beginning to end and prints its entire content to the terminal. This is the most common use of cat.


Example 2: Display the content of multiple files

# Display the content of file1.txt followed immediately by file2.txt
cat file1.txt file2.txt

Explanation: By providing more than one filename, cat will display the content of each file sequentially. The content of file2.txt will start on the line immediately following the last line of file1.txt.


Example 3: Concatenate files into a new file

# Combine the contents of chapter1.txt and chapter2.txt into a new file named book.txt
cat chapter1.txt chapter2.txt > book.txt

Explanation: This command demonstrates the "concatenate" function by reading chapter1.txt and chapter2.txt. Instead of displaying the output, the > redirection operator sends the combined text into a new file called book.txt.


Example 4: Display file content with line numbers

# Show the content of a script with each line numbered
cat -n script.sh

Explanation: The -n option instructs cat to number all output lines, starting with 1. This is very helpful for discussing or debugging code and configuration files.


Example 5: Suppress repeated empty lines

# Display a configuration file, squeezing multiple blank lines down to a single blank line
cat -s httpd.conf

Explanation: The -s (squeeze-blank) option is useful for cleaning up the output of files that have excessive empty lines. It replaces sequences of two or more adjacent empty lines with a single one.


Example 6: Append file content to another file

# Add the content of new_logs.txt to the end of an existing master_log.txt file
cat new_logs.txt >> master_log.txt

Explanation: Using the >> append operator prevents overwriting the destination file. This command adds the full contents of new_logs.txt to the very end of master_log.txt.


Example 7: Display non-printing characters

# Display a file and show tab characters as ^I and end of lines as $
cat -ET /path/to/file

Explanation: The -E option shows a $ at the end of each line, and the -T option displays tab characters as ^I. This is useful for troubleshooting file formatting issues that are not visible in a standard view.