WCC logo

CIS120Linux Fundementals

The cat Command

The cat (short for "concatenate") command is one of the most frequently used commands in Linux, providing versatile functionalities such as reading and concatenating files, creating new files, and appending data to existing ones. Mastering the cat command is essential for efficient file management in a Linux environment.

Syntax

cat [OPTION]... [FILE]...
    

Common Options

Option Description
-A Show all, equivalent to -vET
-b Number non-blank output lines
-e Equivalent to -vE
-E Display $ at the end of each line
-n Number all output lines
-s Suppress repeated empty output lines
-T Display TAB characters as ^I
-v Use ^ and M- notation, except for LFD and TAB

Examples

To display the contents of a file, use:

cat filename.txt
    

This command outputs the contents of filename.txt to the terminal.

If you want to concatenate multiple files, you can use:

cat file1.txt file2.txt
    

This merges the contents of file1.txt and file2.txt and displays the combined content.

Creating a new file can be done with:

cat > newfile.txt
    This is a new file created using the cat command.
    Press Enter then Ctrl+D to save and exit.
    

Output:

cat newfile.txt
    This is a new file created using the cat command.
    

This command creates newfile.txt with the provided content.

To append data to an existing file, use:

cat >> existingfile.txt
    Appending this text to the existing file.
    Press Enter then Ctrl+D to save and exit.
    

Output:

cat existingfile.txt
    Appending this text to the existing file.
    

This appends the provided content to existingfile.txt.

For displaying line numbers, the command is:

cat -n filename.txt
    

This displays the contents of filename.txt with line numbers.

If you want to suppress repeated empty lines, use:

cat -s filename.txt
    

This command displays the contents of filename.txt but suppresses repeated empty lines.

To display $ at the end of each line, use:

cat -E filename.txt
    

This command displays the contents of filename.txt and adds a $ at the end of each line.

To show all characters, including non-printing characters, use:

cat -A filename.txt
    

Suppose file.txt contains:

John Doe
    Jane Smith
    
    Mike Johnson
    

Output:

John Doe$
    Jane Smith$
    $
    Mike Johnson$
    

This command displays the contents of filename.txt with non-printing characters made visible.

You can combine multiple options as well:

cat -nE filename.txt
    

This command displays the contents of filename.txt with line numbers and $ at the end of each line.

Summary

The cat command is a powerful tool in Linux for displaying, creating, and concatenating files. Understanding its options and applications can greatly enhance your efficiency when working with text files in the terminal.