Skip to content
Default image

Linux cat command

July 1, 2022

cat (concatenate) is a command used to print the contents of a text file. You can use it to print contents of documents, css files, js files, linux config files etc.

This command is installed by default in Linux distributions and it doesn’t have to be installed separately.

cat command syntax

cat [options] filename(s)

[options] - will add additional instructions to the command

As seen in the above example, the most common and basic use of this command is to use it without options. You can also use in this basic state to print the contents of multiple files, by specifying the file names.

Create a new file using the cat command

We can use the cat command to create a file and add content to it -there are other ways to create files/directories in linux, but in this post we will focus only on the cat command. The syntax for creating a new file with cat is:

cat > newfile.txt

">" - operator used to redirect the output to a file

Once you press enter on your keyboard, the cursor will move to the next line where you can add the content. In order to save the changes and exit the prompt press ctrl+d.

If we cat newfile.txt we will see that the content was saved

Redirect content

Instead of printing the content of a file or multiple files in the terminal, with the help of the > operator we can redirect the contents in a file.

cat file.txt > redirect.txt
cat file1.txt file2.txt > file3.txt

If the destination file does not exist, it will be created.

Please keep in mind that if you use the > operator to redirect to an existing file, the redirect will overwrite the contents of the file.

We can avoid this situation by using the >> operator, which will append the content to the existing file.

cat -n

When going through large files, sometimes it’s helpful to show the line numbers as well in the output.

In order to do this we use the -n operator

cat -e

Using -e will show the $ symbol at the end of every line and spaces between lines.

cat -s

Sometimes, when going through a file you might come across repeated empty lines that make it a little harder to read all the output. The -s operator will suppress the empty lines

This is it for this post. Thank you for reading.

Remember that you can always check the manual to see how to use a command and don’t be afraid to google it.