Master the cat Command: Your Linux File Storyteller

Display and combine files with the cat command!

What is the cat Command?

Imagine the Linux filesystem as a library, and the cat command—short for concatenate—as your storyteller, reading file contents aloud or weaving multiple files together. Type cat file.txt to display file.txt’s contents in the terminal.

Why cat is Essential

View Files

Quickly display file contents in the terminal.

Combine Files

Concatenate multiple files into one.

Scripting Utility

Use in scripts to process or redirect file contents.

Syntax and Options

The cat command is versatile:

cat [options] file...
        

Key options:

  • -n: Number all output lines.
  • -b: Number non-blank lines.
  • -s: Squeeze multiple blank lines into one.
  • -v: Show non-printing characters.

Real-World Examples

1. Display a File

Type this:

cat note.txt
        

Output:

Hello, Linux!
        

2. Concatenate Files

Combine multiple files:

cat file1.txt file2.txt > combined.txt
        

Creates combined.txt with contents of both files.

3. Number Lines

Display with line numbers:

cat -n script.sh
        

Output:

     1  #!/bin/bash
     2  echo "Hello, Linux!"
        

4. Squeeze Blank Lines

Reduce multiple blank lines:

cat -s file.txt
        

Output: Multiple blank lines reduced to one.

5. Scripting with cat

Create a file from input:

#!/bin/bash
cat > newfile.txt << EOF
Line 1
Line 2
EOF
        

Creates newfile.txt with specified content.

Advanced Usage

Elevate cat with these techniques:

  • Pipe to Other Commands: Use cat file.txt | grep "pattern" to filter content.
  • Append Output: Use cat file.txt >> existing.txt to append instead of overwrite.
  • Display Non-Printing Characters: Use cat -v to show control characters.
  • Read from Stdin: Use cat - to read from standard input.

Example: Filter lines with grep:

cat log.txt | grep "ERROR"
        

Pro Tips

Quick View: Use cat for small files; prefer less for large ones.

Combine with Redirects: Use cat *.txt > all.txt to merge files.

Alias Shortcut: Set alias catn='cat -n' for numbered output.

Common Mistakes to Avoid

Avoid these pitfalls with cat:

  • Large Files: Avoid cat for large files; use less or more.
  • Binary Files: cat on binary files can garble output; use hexdump or strings.
  • Overwriting Files: Use >> to append, not >, to avoid overwriting.

Explore More Linux Commands

Master Linux with our expert guides!