Skip to content

The cat Command: Displaying File Contents

Summary

The cat command is a fundamental utility in Linux for displaying the contents of one or more files. It's a quick and easy way to view text files without opening a dedicated text editor.

Introduction

The cat command, short for "concatenate," is primarily used to output the contents of files to the standard output (usually your terminal screen). While its name implies concatenation, it's more commonly used for simply viewing file content. It is one of the most basic, yet indispensable, commands in any Linux user's toolkit.

Use case and Examples

Displaying a Single File

cat myfile.txt
This command displays the entire content of the myfile.txt file on your terminal.

Displaying Multiple Files

cat file1.txt file2.txt file3.txt
This command concatenates and displays the contents of file1.txt, file2.txt, and file3.txt in sequence.

Creating a New File by Concatenating Existing Files

cat file1.txt file2.txt > newfile.txt
This command concatenates the content of file1.txt and file2.txt and redirects the output to create a new file named newfile.txt. If newfile.txt exists, its contents will be overwritten.

Appending to an Existing File

cat file1.txt >> existingfile.txt
This command appends the content of file1.txt to the end of existingfile.txt. If existingfile.txt doesn't exist, it will be created.

Using cat with pipes

ls -l | cat
This command pipes the output of ls -l (a listing of files with detailed information) to cat, which then displays it on the terminal. Although not typically the best use case for cat, it demonstrates its ability to work with standard input. less or more are often more suitable for viewing long outputs.

Commonly used flags

Flag Description Example
-n Numbers all output lines cat -n myfile.txt (Displays file content with line numbers)
-b Numbers non-blank output lines, overrides -n cat -b myfile.txt (Numbers only the lines that contain text)
-s Suppresses repeated empty output lines cat -s myfile.txt (Reduces multiple consecutive empty lines to a single empty line)
-E Displays a $ at the end of each line cat -E myfile.txt (Useful for identifying trailing spaces)
-T Displays TAB characters as ^I cat -T myfile.txt (Helps to visualize tab characters in the file)


Share on Share on

Comments