Linux Cat command
The Linux Cat command is one of the most commonly used Linux commands. It is predominantly used to output the contents of a file on the command line. However, there are a number of other uses, which are discussed in this article.
What is the Linux Cat command?
Despite its name, the Linux Cat command has nothing to do with cats. In fact, the command does something quite mundane: The Linux Cat command reads the content of files and prints them on the command line. The origin of the name comes from the term ‘concatenate’ - more about that below.
Let’s look at the basic pattern of a call to the Linux Cat command. As you can see, we first write ‘cat’, followed by options, and then the name or paths of the file(s) to be output:
cat [options] <file name(s)>
The Linux Cat command is part of the ‘GNU Core Utilities’ (Coreutils) which is a collection of basic command line commands. The Coreutils are ‘Free and Open Source Software’ (FOSS) and are available in almost all Linux distributions. Furthermore, the Linux Cat command is available under macOS and Windows when using the ‘Windows Subsystem for Linux’ (WSL/WSL2).
You can find out whether Linux Cat is available on your system by doing the following: Open a command line and run the command ‘which cat’. If the Linux Cat command is available on your system, the path of the cat binary (e.g. ‘/bin/cat’) is displayed. If an error message is displayed, the Linux cat command is not available on your system.
Options of the Linux Cat command
Like most command line commands, Linux Cat is controlled by optional parameters when invoked. These options follow the name of the command. It should be noted that they are case sensitive. Usually there are two spellings for most options:
- Short form: -<options shortcut>, e.g. ‘cmd -h’
The short form is not very meaningful. Instead, several options can be combined into one, e.g. ‘ls -la’ instead of ‘ls -l -a’. The short form is well suited for fast working with known commands on the command line.
- Long form: --<options name>, e.g. ‘cmd –help’
The long form is easy to understand, but takes more time to type and takes up more space. The long form is well suited for creating scripts. The meaningful option names serve the documentation.
The table below lists the main options of the Linux Cat command:
The table below lists the main options of the Linux Cat command:
Option | Explanation |
---|---|
-h, --help | Show Linux Cat command help |
-n | Number lines of the output |
-s | Combine several blank lines into one |
-b | Number all lines of the output except for blank lines |
-v | Output invisible characters |
-e | Like -v, including end-of-line marker |
-t | Like -v, including tab marker |
-et | Combination of -e and -t; output all invisible characters |
What does concatenate mean?
The name of the Linux Cat command comes from ‘concatenate’, itself derived from the Latin term ‘catena’ meaning chain. Concatenation is an important concept in computer science. The term describes the stringing or joining of elements of similar container data structures. Most languages allow for multiple arrays or strings to be concatenated into one array or string. In this case, the individual elements of the concatenated containers are combined in a new container while retaining the sequence.
Here’s a simple example in pseudocode, in which we pass several strings to the Cat function that are combined into a single string:
cat("Peter ", "and ", "Paul") -> "Peter and Paul"
The Linux Cat command conceptually does the same thing: as elements, it processes lines grouped within files.
Different programming languages use different symbols for the string concatenation operator. Let’s look at a few examples of popular programming languages. In all cases, the result of the concatenation is the string ‘Peter and Paul’:
Operator | Language(s) | Example |
---|---|---|
+ | Java, JavaScript, Python | Peter + "and" + " Paul" |
. | PHP, Perl | Peter . "and" . " Paul" |
.. | Lua | Peter .. "and" .. " Paul" |
~ | Twig | Peter ~ "and" ~ " Paul" |
& | VisualBasic | Peter & "and" & " Paul" |
In some languages, notably Python, the same operator is used for concatenating other container data structures such as lists:
# Concatenate lists
[1, 2, 3] + [45, 56, 67]
# -> [1, 2, 3, 45, 56, 67]
# mind you NOT:
# [[1, 2, 3], [45, 56, 67]]
# Concatenate tuples
(1, 2) + (33, 44)
# -> (1, 2, 33, 44)
The statistics language ‘R’ is an interesting case because it doesn’t know a concatenation operator. Instead, is uses the ‘c()’ function. Take a guess what the ‘c’ stands for! Correct: ‘concatenate’. The following code shows the nested concatenation of several values:
c(c(1, 2, 3), c(45, 56, 67))
# -> 1, 2, 3, 45, 56, 67
How to use the Linux Cat command in practice?
The actual use of the Linux Cat command is limited. It follows the UNIX philosophy ‘do one thing and do it well’. Most usage scenarios result from chaining the command with other commands. Redirections of the standard input and output are used. Specifically, these are so-called pipes and redirects. These are provided by the shell; their use extends across all commands:
Redirection | Symbol | Use | Explanation | ||
---|---|---|---|---|---|
Pipe | cmd1 | cmd2 | Forward output of command cmd1 to input of command cmd2 | ||
Input redirect | < | cmd < data | Input to command cmd read from file data | ||
Output redirect | > | cmd > data | Write the output of the cmd command to the data file; if necessary, the existing file will be overwritten. | ||
Output redirect | >> | cmd >> data | Write the output of the cmd command to the data file; if necessary, the existing file will be extended. |
The Linux Cat command is often used with a number of other Linux commands. Let's look at some of the most common ones:
Let’s consider the common usage scenarios of the Linux Cat command.
Using Linux Cat to output files on the command line
Perhaps the most common use of Linux Cat is to output the entire contents of a file on the command line. This is useful when you need to take a quick peek at a file. And unlike opening the file in an editor, you don’t need to worry about accidentally changing the file. Here is an example of outputting a file on the command line:
cat ./path/to/file.txt
Let’s look at a few common scenarios. Imagine you are logged in via SSH to a server running WordPress. You are in the WordPress root directory and want to view the contents of the configuration file ‘wp-config.php’. The following Linux Cat command will be sufficient:
cat wp-config.php
Often the output of a file on the command line is sufficient. However, in some cases we want to copy the contents of the file to the clipboard. Furthermore, visible output on the command line may pose a risk for sensitive data. In both cases, it is a good idea to forward the output of the Linux Cat command to a program that writes the data to the clipboard. Under macOS, the command line tool ‘pbcopy’ is available for this purpose; under Windows with WSL/2 and the various Linux distributions, equivalent tools such as ‘clip’ or ‘xclip’ are available.
Consider the following example to copy our SSH public key to set up a GitHub repository. Let’s assume that the key named ‘id_rsa.pub’ is located in the ‘.ssh/’ directory in our user directory. In macOS, we can issue the following call to the Linux Cat command:
cat ~/.ssh/id_rsa.pub > pbcopy
As the name of the Linux Cat command implies, several files can be combined and output at once. Imagine lists of fruits, vegetables, and dairy products stored in three files in the directory ‘food/’. With the following call to Linux Cat, we combine all three lists into one and write it to the file ‘food.txt’:
cat ./food/fruit.txt ./food/veggies.txt ./food/dairy.txt > food.txt
As usual on the command line, we can use the wildcard ‘*’ to select all files in a directory:
cat ./food/*.txt > food.txt
Writing text to a file with the Linux Cat command
Using the output redirects mentioned above, you can write text to a file using Linux Cat. There are three ways to do this:
-
- Create a new file to enter text in.
- Overwrite an existing file with text.
- Append the entered text to an existing file.
Let’s take a look at the three scenarios. First, we write text from the command line to a non-existent file:
- Invoke Linux Cat command and forward output to a non-existent file. The command takes data from standard input until the end-of-file (‘EOF’) character is read:
cat > new.txt
- Enter the desired text on the command line.
- End the input with the key combination [Ctrl] + [D]. This key combination corresponds to the end-of-file character.
The text is now contained in the ‘new.txt’ file. You can verify this by calling the command ‘cat new.txt’.
Now let’s use the same approach to append the text to an existing file:
- Call Linux Cat command and forward output to existing file:
cat >> existing.txt
- Enter the desired text on the command line.
- Terminate the input with the key combination [Ctrl] + [D].
If we use the symbol ‘>’ instead of the output forwarding ‘>>’, the existing file will be overwritten with the entered text. Be careful with this because the previous content of the file will be irrevocably lost!
Using the Linux Cat command to prepare data for further processing
A common use of the Linux Cat command is to combine data from multiple files. Often the combined data is passed through filters to prepare it for further processing. It is predominantly used when similar data is spread to several files. Each file contains one entry per line. For example, think of lists of names, IP addresses, or the like.
To get an overview of all characteristics of the data, the following task arises: we want to combine all entries and remove any duplicate entries. Finally, we want to sort the entries and write them to a new file. As a concrete example, let’s imagine we have a set of text files. Each file contains the names of the actors of a certain episode of the comic series ‘The Simpsons’. If we combine the entries of all files as described, we get a list of all the Simpsons actors.
The files described in our example with Simpsons actors would schematically look something like this:
simpsons-1.txt | simpsons-2.txt | simpsons-3.txt |
---|---|---|
Lisa | Bart | Bart |
Marge | Lisa | Maggie |
Homer | Homer | Nelson |
Flanders | Milhouse |
Let us further assume that the individual text files are located in the directory ‘simpsons/’. Then the following call of the Linux Cat command, concatenated with the commands ‘uniq’ and ‘sort’, is sufficient to write the list of all Simpsons actors into the file ‘simpsons.txt’:
cat ./simpsons/*.txt | uniq | sort > simpsons.txt
Using the Linux Cat command to number lines of a text file
A common use of the Linux Cat command is to number the lines of a text file. Let’s imagine we have a text file with entries, one entry per line. Now we want to prefix each line with the line number. This is useful, for example, when we want to share the resulting file for review. This way both parties can refer to specific lines in their correspondence.
With the Linux Cat command, numbering is simple. We use the ‘-n’ option and an output redirection:
cat -n doc.txt > doc.numbered.txt
In the described scenario, it may be useful to number all lines except for blank lines. Furthermore, we combine several blank lines into one. For this we use the combination of the options ‘-s’ and ‘-b’:
cat -sb doc.txt > doc.numbered.txt
Combining template files with the Linux Cat command
A well-known pattern from web programming is to assemble documents from set pieces. Combining so-called template parts with unique ones results in diverse documents with a consistent structure. Normally, one uses PHP with the ‘include’ statement or a special template language like Twig to this end. However, the principle can be implemented with the Linux Cat command.
Let's assume we have several template parts in the ‘parts/’ directory. Header and footer should be identical across all documents. The structure and content of the header and footer are defined in the files ‘header.html’ and ‘footer.html’. Furthermore, several files with the actual content of the documents exist in the directory ‘main/’. The finished documents are stored in the output directory ‘www/’. To create a document, the following call of the Linux Cat command is sufficient:
cat ./parts/header.html ./main/home.html ./parts/footer.html > ./www/index.html
Another usage scenario: a codebase is to be provided with a license text for publication. The license is to be inserted at the beginning of each code file. Let's imagine the following directory layout:
- Python source code files with extension ‘.py’ in the directory ‘src/’.
- A license file ‘license.py’ in the ‘inc/’ directory
- An initially empty directory ‘dist/’ to store the processed files
We use the Linux Cat command inside a for-loop. On each pass of the loop, the same license file is concatenated with one of the source code files. The result is written to a new source code file with the same name:
for file in ./src/*.py ; do
cat ./inc/license.py "$file" > "./dist/${file}"
done
Merging split files with the Linux Cat command
Mostly Linux Cat is used to process plain text files. However, the command also works with binary files. This is useful for some scenarios. First, the Linux commands ‘split’ or ‘csplit’ can be used to reassemble files that have been split into multiple parts. Here’s the general approach:
# Filename of the file to be split
file_name="./path/to/file"
# We explicitly specify the file extension to append it after merging
extension="txt"
# Split original file into 10-kilobyte chunks with prefix “part_”.
split -b 10k "${file_name}.${extension}" part_
# Merge individual pieces into a new file
cat part_* > combined
# Restore original file extension
mv combined "combined.${extension}"
On the other hand, the Linux Cat command is useful to combine partial downloads. Many tools can interrupt downloads and resume them later. This is especially useful when downloading a large file over a weak network connection. Feel free to try the example on your own system:
# Create test folder on the desktop
mkdir ~/Desktop/cat-test/
# Switch to test folder
cd ~/Desktop/cat-test/
# Public domain cat image from WikiMedia
image=https://upload.wikimedia.org/wikipedia/commons/f/fa/Cat_using_computer.jpg
# Download image with "curl" in two parts
curl -s -r 0-500000 "$image" -o first-half &
curl -s -r 500001- "$image" -o second-half &
wait
# Combine parts and write to JPEG file
cat first-half second-half > image.jpg
Combining data streams with the Linux Cat command
The Linux cat command can be used to combine data streams in video processing. The general pattern is shown in the example below. First, we create several short video streams from a JPEG image using the ffmpeg command. Then we combine them into one continuous video:
# Create a loop from the image
ffmpeg -y -loop 1 -i image.jpg -t 3 \
-c:v libx264 -vf scale=w=800:h=-1 \
still.ts
# Create a fade-in from the image
ffmpeg -y -loop 1 -i image.jpg -t 3 \
-c:v libx264 -vf scale=w=800:h=-1,fade=in:0:75 \
fadein.ts
# Create a fade from the image
ffmpeg -y -loop 1 -i image.jpg -t 3 \
-c:v libx264 -vf scale=w=800:h=-1,fade=out:0:75 \
fadeout.ts
# Combine fade up, loop and fade down
cat fadein.ts still.ts fadeout.ts > video.ts
When not to use the Linux Cat command?
The unnecessary use of the Linux cat command is a well-known ‘anti-pattern’. Numerous articles describe this pattern, and there is even a ‘Useless Use of Cat Award’. As a rule of thumb, Linux Cat should be used when combining multiple files. Processing a single file is usually possible without cat.
Let’s look at an approach to minimise unnecessary use of the Linux cat command. In forum posts and blog articles you’ll often spot the following pattern:
cat example.txt | less
The Linux cat command is used to read a single file. The output is piped to the ‘less’ command to display the contents of the file page by page. However, this can be done more simply:
less < example.txt
We call the ‘less’ command and use the shell’s input redirection to read in the file. But this approach can be simplified even further:
less example.txt
Instead of using input redirection, we pass the file to be processed to the ‘less’ command. This is because almost all Linux commands take the file name(s) as parameters.
What are alternatives to the Linux Cat command?
As previously mentioned, Linux cat is often used unnecessarily. Alternatives exist for some of the most common usage scenarios. Here are three examples:
Command | Alternative use | Example |
---|---|---|
less / more | Output file/content page by page to command line | less file.txt, more file.txt |
touch | Create new, empty file | touch new.txt |
echo | Write text to file | echo ‘Text’ > file.txt |
What commands are similar to Linux cat?
There are a number of Linux commands that are similar to the Cat command. As a little inside joke, the names of these commands are often based on Cat. First, there is the tac command, which is cat in reverse. And that’s also how the tac command works: just like Linux Cat, but with a reversed output. So when the tac command is called for a single file, the last line is output first, instead of the first as with Cat.
Another command with a similar name to Linux Cat is the nc command, an abbreviation for ‘Netcat’. The command is often referred to as the ‘Swiss Army knife for TCP/IP’. Instead of operating on local files like cat, Netcat reads and writes data over network connections. You can learn more in our article on the topic.
A newer alternative to the Linux cat command is the bat command. Its Github page refers to it as ‘a cat clone with wings’. The bat command retains the basic functionality of the Linux cat command, but provides some convenient features. In particular, the bat command adds syntax highlighting to the output of source code files.