Skip to Content
TutorialsLinux Mastery GuideEssential Linux Commandscat - Concatenate and Display Files

Understanding the cat Command in Linux: Concatenate and Display Files

1. Introduction

The cat command is one of the most frequently used utilities in Linux and Unix-like operating systems. Its name is short for concatenate, which hints at its primary function: to link files together and print their contents to the standard output (usually the terminal screen). However, cat is also commonly used to simply display the content of a single file, create small files, and as part of command pipelines.

This guide will explore the syntax, core functionalities, various options, and practical applications of the cat command.

2. Basic Syntax

The basic syntax for the cat command is:

# Basic syntax of the cat command $ cat [OPTION]... [FILE]...
  • [OPTION]...: Optional flags that modify cat’s behavior, such as numbering lines (-n) or showing non-printing characters (-A).
  • [FILE]...: One or more filenames (or paths to files) whose contents cat will process. If no file is specified, or if a single hyphen (-) is used, cat reads from standard input (e.g., keyboard input or piped data).

3. Core Use Cases with Examples

To demonstrate cat’s capabilities, let’s set up a test environment with sample files.

Setup

# Create a directory named 'cat_test_area' for testing purposes $ mkdir cat_test_area # Change into the newly created directory $ cd cat_test_area # Create sample files # Create 'file1.txt' with two lines $ echo "This is the first line of file1." > file1.txt $ echo "This is the second line, also in file1." >> file1.txt # Create 'file2.txt' with one line $ echo "Content from file2." > file2.txt # Create 'file3.md' with two lines using echo -e for newline $ echo -e "Line A\nLine B" > file3.md # Verify that the files have been created $ ls

Output:

file1.txt file2.txt file3.md

3.1. Displaying the Content of a Single File

The most common use of cat is to quickly view a file’s contents.

# Display the content of 'file1.txt' $ cat file1.txt

Output:

This is the first line of file1. This is the second line, also in file1.

3.2. Displaying the Content of Multiple Files

cat concatenates and displays multiple files in sequence.

# Display the contents of 'file1.txt' and 'file2.txt' in sequence $ cat file1.txt file2.txt

Output:

This is the first line of file1. This is the second line, also in file1. Content from file2.

3.3. Concatenating Files into a New File (Output Redirection)

Combine multiple files and save the result into a new file using output redirection (>).

# Concatenate 'file1.txt' and 'file2.txt' into 'combined_files.txt' $ cat file1.txt file2.txt > combined_files.txt # Verify the content of the new file $ cat combined_files.txt

Output:

This is the first line of file1. This is the second line, also in file1. Content from file2.

3.4. Appending File Contents to an Existing File (Output Redirection)

Use >> to append contents to an existing file without overwriting it.

# Append 'file3.md' to 'combined_files.txt' $ cat file3.md >> combined_files.txt # Verify the appended content $ cat combined_files.txt

Output:

This is the first line of file1. This is the second line, also in file1. Content from file2. Line A Line B

3.5. Creating a Small File (Using Standard Input)

Run cat without file arguments to read from standard input until Ctrl+D is pressed.

# Create a new file by typing directly into standard input $ cat > new_manual_file.txt This is line one typed manually. This is line two. # Press Ctrl+D to save and exit # Verify the content of the new file $ cat new_manual_file.txt

Output:

This is line one typed manually. This is line two.

3.6. Using a Hyphen (-) for Standard Input in a Concatenation

A hyphen (-) acts as a placeholder for standard input within a file list.

# Concatenate 'file1.txt', standard input, and 'file2.txt' into 'mixed_input.txt' $ cat file1.txt - file2.txt > mixed_input.txt This is keyboard input for the middle part. # Press Ctrl+D to end input # Verify the content $ cat mixed_input.txt

Output:

This is the first line of file1. This is the second line, also in file1. This is keyboard input for the middle part. Content from file2.

3.7. Using cat in Pipelines

cat is often used to feed file contents into other commands via pipelines.

# Use cat to display lines containing 'first' from 'file1.txt' $ cat file1.txt | grep "first"

Output:

This is the first line of file1.

4. Key Options Explained (with Examples)

cat offers several options to modify its output, each serving specific purposes.

4.1. -n, --number: Number All Output Lines

Purpose: Prepends a line number to each line, including blanks.

Syntax: cat -n FILE...

# Display 'file1.txt' with all lines numbered $ cat -n file1.txt

Output:

1 This is the first line of file1. 2 This is the second line, also in file1.

4.2. -b, --number-nonblank: Number Non-Empty Output Lines

Purpose: Numbers only non-empty lines, overriding -n. It is similar to -n, but only numbers lines that are not empty (i.e., lines that contain at least one non-whitespace character).

Syntax: cat -b FILE...

# Create a file with blank lines $ echo -e "First line\n\nThird line (after blank)" > file_with_blanks.txt # Number only non-empty lines $ cat -b file_with_blanks.txt

Output:

1 First line 2 Third line (after blank) # Note: The blank line is not numbered

4.3. -s, --squeeze-blank: Suppress Repeated Empty Output Lines

Purpose: If the input contains multiple consecutive empty lines, -s squeezes them down to a single empty line in the output.

Syntax: cat -s FILE...

# Create a file with multiple blank lines $ echo -e "Content A\n\n\nContent B\n\nContent C" > file_many_blanks.txt # Squeeze multiple blank lines into single blank lines $ cat -s file_many_blanks.txt

Output:

Content A Content B Content C # Multiple blank lines are reduced to single blank lines

4.4. -E, --show-ends: Display $ at End of Each Line

Purpose: Appends a $ character to the end of each output line. This is useful for visualizing trailing whitespace or ensuring lines end where you expect.

Syntax: cat -E FILE...

# Create a file with trailing spaces $ echo "Line with trailing spaces " > file_trailing_space.txt $ echo "Normal line" >> file_trailing_space.txt # Show line endings with $ $ cat -E file_trailing_space.txt

Output:

Line with trailing spaces $ Normal line$

4.5. -T, --show-tabs: Display TAB Characters as ^I

Purpose: Represents tab characters in the output as ^I. This helps identify where tabs are used versus spaces.

Syntax: cat -T FILE...

# Create a file with tabs $ echo -e "Column1\tColumn2\tColumn3" > file_with_tabs.txt # echo -e interprets \t # Show tabs as ^I $ cat -T file_with_tabs.txt

Output:

Column1^IColumn2^IColumn3

4.6. -A, --show-all: Equivalent to -vET

Purpose: This is a convenient shorthand option that combines the effects of -v (show non-printing characters, see below), -E (show ends), and -T (show tabs). It provides the most comprehensive view of normally invisible characters.

Syntax: cat -A FILE...

# Show all non-printing characters in 'file_with_tabs.txt' $ cat -A file_with_tabs.txt

Output:

Column1^IColumn2^IColumn3$

4.7. -v, --show-nonprinting: Use ^ and M- Notation, Except for LFD and TAB

Purpose: Displays non-printing characters (control characters) using ^ notation (e.g., ^C for Ctrl+C) and characters with the high bit set using M- notation (meta notation), except for Line Feed (newline) and Tab characters, which are typically handled by -E and -T respectively (or implicitly by -A).

Syntax: cat -v FILE...

# Create a file with a bell character (Ctrl+G) $ printf "This has a bell \a character.\n" > file_with_bell.txt # Show non-printing characters $ cat -v file_with_bell.txt

Output:

This has a bell ^G character.
💡

Note: In Linux, \a is an escape sequence that represents the bell character. When included in text or output, it triggers the terminal to produce a sound, often an audible beep, to alert the user. This character can be used in various contexts, like when printing text to the terminal or in shell scripts to signal an event or alert.

4.8. --help: Display Help and Exit

Purpose: Shows a summary of cat options and usage.

Syntax: cat --help

# Display help text for cat $ cat --help

4.9. --version: Output Version Information and Exit

Purpose: Displays the version of the cat utility.

Syntax: cat --version

# Show version information for cat $ cat --version

5. Combining Options

Options can be combined to customize output further.

5.1. Numbering and Squeezing Blank Lines

Combine -n (number all lines) and -s (squeeze blank lines).

# Create a file with multiple blank lines $ echo -e "Line 1\n\n\nLine 4" > test_combine.txt # Number all lines and squeeze multiple blank lines $ cat -ns test_combine.txt

Output:

1 Line 1 2 3 Line 4

5.2. Showing Tabs and Line Endings

Combine -E (show line endings) and -T (show tabs), equivalent to parts of -A.

# Create a file with tabs and a literal $ $ echo -e "Tab\tHere$" > test_combine2.txt # Note: $ is literal here # Show tabs as ^I and line endings as $ $ cat -ET test_combine2.txt

Output:

Tab^IHere$$

(First $ is literal from echo, second $ is from -E)

6. Handling Special Cases

6.1. Filenames Starting with Hyphen

Filenames starting with a hyphen may be mistaken for options. Use -- to separate options from files.

# Create a file named '-problem.txt' $ echo "Content of a tricky file." > ./-problem.txt # Use '--' to separate options from filenames $ cat -- -problem.txt

Output:

Content of a tricky file.

Alternative: Prefix with a path.

# Use path to avoid hyphen confusion $ cat ./-problem.txt

Output:

Content of a tricky file.

6.2. Filenames with Spaces

Quote or escape spaces in filenames.

# Create a file with spaces in its name $ echo "File with spaces." > "my spaced file.txt" # Display its content using quotes $ cat "my spaced file.txt"

Output:

File with spaces.

Alternative: Escape spaces.

# Display using escaped spaces $ cat my\ spaced\ file.txt

Output:

File with spaces.

6.3. Permissions

  • Reading: Requires read (r) permission on the file.
  • Writing: Requires write (w) permission on the target directory or file for redirection.

Check permissions:

# Check permissions of 'file1.txt' $ ls -l file1.txt

Output (example):

-rw-r--r-- 1 user user 64 May 13 14:17 file1.txt

6.4. Directories

cat cannot process directories.

# Attempt to cat a directory $ mkdir my_dir $ cat my_dir

Output:

cat: my_dir: Is a directory

Use ls for directories:

$ ls my_dir

6.5. Device Files

cat can read device files, but this may produce continuous or unreadable output.

# Read from /dev/random (use with caution, press Ctrl+C to stop) # $ cat /dev/random # Prints random bytes # $ cat /dev/zero # Prints endless null bytes

7. Frequently Asked Questions (FAQ)

7.1. What is the main purpose of the cat command?

Answer: To concatenate files and print their content to standard output. It’s also commonly used to display single files.

Example:

# Display content of a single file $ cat file.txt

7.2. How can I view a large file page by page?

Answer: cat is not ideal for large files. Use pagers like less or more.

Example:

# View a large file page by page $ less large_file.txt $ more large_file.txt

7.3. What’s the difference between cat file > new_file and cat file >> new_file?

Answer:

  • >: Overwrites new_file if it exists, or creates it if it doesn’t.
  • >>: Appends to new_file if it exists, or creates it if it doesn’t.

Example:

# Overwrite 'new_file.txt' $ cat file1.txt > new_file.txt # Append to 'new_file.txt' $ cat file2.txt >> new_file.txt

7.4. Why is it sometimes called “Useless Use of cat” (UUOC)?

Answer: UUOC refers to unnecessary cat usage when a command can directly read a file, e.g., cat file | grep pattern vs. grep pattern file. While not harmful, it’s less efficient.

Example:

# UUOC example $ cat file1.txt | grep "first" # Better alternative $ grep "first" file1.txt

7.5. Can cat be used to create files?

Answer: Yes, by redirecting standard input.

Example:

# Create a new file with standard input $ cat > new_file.txt Type your content here... # Press Ctrl+D to save and exit

7.6. How do I see hidden characters like tabs or end-of-line markers?

Answer:

  • -T: Shows tabs as ^I.
  • -E: Shows $ at line ends.
  • -A: Shows all non-printing characters (-vET).

Example:

# Show all non-printing characters $ cat -A file_with_tabs.txt

7.7. Does cat modify original files?

Answer: No. cat only reads from the specified files and prints to standard output. If you use output redirection (> or >>), you are creating or modifying a different file (or the same file if you do cat file > file, which usually empties the file first!).

7.8. Can cat handle binary files?

Answer: Yes, cat will attempt to print the raw byte stream of a binary file to your terminal. This will almost always result in garbled, unreadable output and can sometimes mess up your terminal settings (use reset command to fix your terminal if this happens). Use tools like hexdump, xxd, or strings for inspecting binary files.

Example:

# Inspect a binary file $ hexdump -C binary_file

7.9. How to add separators when concatenating multiple files?

Answer: cat doesn’t support separators directly. Use a loop or other commands.

Example:

# Add separators between files $ for f in file1.txt file2.txt; do cat "$f"; echo "---SEPARATOR---"; done > combined_with_sep.txt

7.10. What does cat < file.txt do?

Answer: Equivalent to cat file.txt. The < redirects standard input from file.txt, but it’s often considered UUOC since cat can take filenames directly.

Example:

# Redundant use of < $ cat < file.txt

8. Conclusion

The cat command is an essential tool in the Linux ecosystem, offering simplicity and power for file manipulation. Its ability to display, concatenate, and create files, combined with options for line numbering, squeezing blank lines, and displaying non-printing characters, makes it indispensable for daily tasks and scripting. By understanding its features and handling edge cases, users can leverage cat to streamline workflows and enhance productivity.

9. cat Command: Reference Table of Key Options

Option(s)DescriptionExample CommandUse Case
(none)Concatenate FILE(s) to standard outputcat file.txtDisplay or concatenate files
-n, --numberNumber all output linescat -n script.shAdd line numbers for reference
-b, --number-nonblankNumber non-empty linescat -b config.iniNumber only non-blank lines
-s, --squeeze-blankSuppress repeated blank linescat -s data.logReduce multiple blank lines to one
-E, --show-endsDisplay $ at line endscat -E textfile.txtVisualize line endings
-T, --show-tabsDisplay tabs as ^Icat -T source_code.pyIdentify tabs in files
-A, --show-allShow all non-printing characters (-vET)cat -A data_fileInspect hidden characters
-v, --show-nonprintingShow control characters in ^/M- notationcat -v binary_snippetDisplay non-printing characters
--helpDisplay help textcat --helpView command usage
--versionShow version informationcat --versionCheck cat version

10. Bonus Content: Stdin, Stdout, Stderr, and Redirection in Linux: A Simple Explanation

  • Stdin (Standard Input):

    • What it is: The default way a program gets its input, like data it needs to work with.
    • Default source: Your keyboard—when you type, the program reads it from stdin.
    • Example: Typing a command like sort and entering names to sort them.
    • Why it matters: Programs can use stdin to get data from anywhere, not just the keyboard.
  • Stdout (Standard Output):

    • What it is: The default place where a program sends its results or output.
    • Default destination: Your screen—output shows up in the terminal.
    • Example: Running ls (or dir on some systems) shows a file list on your screen via stdout.
    • Why it matters: You can see results or send them somewhere else, like a file.
  • Stderr (Standard Error):

    • What it is: A separate channel just for error messages or warnings.
    • Default destination: Your screen, but it’s kept apart from regular output.
    • Example: If you type ls blah, the “file not found” error goes to stderr.
    • Why it matters: Errors don’t mix with normal output, so you can handle them separately.
  • Redirection:

    • What it is: Changing where stdin, stdout, or stderr come from or go to.
    • Common operators:
      • < : Pulls input from a file (e.g., sort < names.txt sorts a file’s content).
      • > : Sends output to a file (e.g., ls > files.txt saves the file list).
      • 2> : Sends errors to a file (e.g., ls blah 2> errors.txt logs the error).
    • Why it matters: Gives you control to use files or other commands instead of defaults.

10.1 Where Are These Concepts Used?

  • Command-Line Operations:

    • Input: Use < to feed a file to a command (e.g., sort < list.txt).
    • Output: Save results with > (e.g., echo "Hello" > greeting.txt).
    • Errors: Capture errors with 2> (e.g., grep "missing" file.txt 2> errors.txt).
  • Scripting and Automation:

    • Combine commands with redirection (e.g., cat data.txt | sort sorts file data).
    • Automate tasks by saving or reading data in scripts.
  • System Administration:

    • Redirect logs to files (e.g., service start > log.txt 2> error.txt).
    • Keep track of errors without cluttering regular output.

10.2 Why Is It Important to Understand These Concepts?

  • Core of Linux:

    • These are basic building blocks for how Linux moves data around.
    • You need them to use the command line effectively.
  • Saves Time:

    • Redirection lets you automate input and output instead of doing things manually.
  • Easier Debugging:

    • Keeping errors (stderr) separate helps you spot and fix problems quickly.
  • More Power:

    • Combine commands and redirection to do complex tasks easily.

Understanding stdin, stdout, stderr, and redirection makes Linux more useful and manageable. Whether you’re running simple commands or writing scripts, these ideas help you work smarter.