Skip to main content

Understanding the `cat` Command in Linux

The cat (short for "concatenate") command is one of the most frequently used commands in Linux. It reads data from files, and outputs their contents. It is commonly used for displaying the content of files, combining copies of different files and creating new ones.


The basic syntax of the cat command is as follows:

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

Here, [OPTION] is used to specify the behavior of the cat command and [FILE] is the name of one or more files you want to read. If no file is specified, or if the - is used as one of the input files, cat will read from the standard input.


Below is a table of common options for cat:

--number-nonblank-bNumber non-empty output lines, overrides -n
--number-nNumber all output lines
--squeeze-blank-sSqueeze multiple adjacent blank lines
--show-ends-EDisplay $ at the end of each line
--show-tabs-TDisplay TAB characters as ^I
--show-nonprinting-vUse ^ and M- notation, except for LFD and TAB


Example 1: Displaying Content of a File

To display the content of a file named example.txt, you would use:

cat example.txt

Example 2: Creating a File with cat

To create a file, you can redirect the output of cat to a file:

cat > newfile.txt

After running the command, type your desired content and then press CTRL+D to save it.

Markdown of newfile.txt:

Hello, this is a text file.
This is the second line.

Example 3: Combining Files

To combine the contents of file1.txt and file2.txt into combined.txt:

cat file1.txt file2.txt > combined.txt

To create file1.txt and file2.txt for this example:

echo -e "First file's content." > file1.txt
echo -e "Second file's content." > file2.txt

Example 4: Using Options with cat

To number all lines of a file:

cat -n example.txt

If you want to squeeze multiple blank lines into a single blank line:

cat -s example.txt

Example 5: Viewing Non-Printable Characters

To see tabs and end-of-line markers in a file:

cat -ET example.txt

Combining cat with Other Commands

The cat command can also be used in conjunction with other Linux commands through pipes (|). For example, to paginate the contents of a file, you can use cat with less:

cat example.txt | less

Or to count the number of lines in a file:

cat example.txt | wc -l

By understanding and using the cat command, Linux users can perform a wide array of file manipulation tasks quickly and efficiently. Whether you are concatenating files, viewing content, or piping data into other commands, cat is an indispensable tool in command-line operations.

What Can You Do Next 🙏😊

If you liked the article, consider subscribing to Cloudaffle, my YouTube Channel, where I keep posting in-depth tutorials and all edutainment stuff for software developers.

YouTube @cloudaffle