Working with files

Linux commands: cat

Learn how the Linux cat command prints a file to standard output, joins multiple files into one with redirection, and shows line numbers with the -n option.

Similar to tail in some way, we have cat. Except cat can also add content to a file, and this makes it super powerful.

In its simplest usage, cat prints a file’s content to the standard output:

cat file

Let’s try it with a real file. Create one with a line of text, then print it:

echo "hello" > a.txt
cat a.txt
hello

If the file doesn’t exist, you get an error instead:

cat missing.txt
cat: missing.txt: No such file or directory

The name cat comes from concatenate, and that’s the second thing it does. You can print the content of multiple files, one after the other:

cat file1 file2

Using the output redirection operator >, you can concatenate the content of multiple files into a new file:

cat file1 file2 > file3

Be careful with >. If file3 already exists, its content is replaced. Using >> instead appends to the file, creating it if it doesn’t exist:

cat file1 file2 >> file3

Here’s the difference in practice. With a.txt containing hello and b.txt containing world:

cat a.txt b.txt > both.txt
cat both.txt
hello
world

Run cat a.txt >> both.txt and both.txt grows to three lines. Run cat a.txt > both.txt and it shrinks back to one.

When looking at source code files, it’s great to see the line numbers. cat prints them with the -n option:

cat -n file1
     1	hello

You can number only the non-blank lines with -b, or squeeze multiple empty lines into one with -s. I use -s on log files that are full of blank lines.

cat is often used in combination with the pipe operator | to feed a file’s content as input to another command: cat file1 | anothercommand.

One thing to keep in mind: cat dumps the whole file at once. For a 5,000-line log, that means 5,000 lines flying past you. When a file is longer than your screen, use less instead, which lets you scroll and search. We’ll see it in the next lesson.

This command works on Linux, macOS, WSL, and anywhere you have a UNIX environment

Lesson completed