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.

Contents

  • What is the Linux Cat command?
  • Options of the Linux Cat command
  • What does concatenate mean?
  • How to use the Linux Cat command in practice?
  • Using Linux Cat to output files on the command line
  • Writing text to a file with the Linux Cat command
  • Using the Linux Cat command to prepare data for further processing
  • Using the Linux Cat command to number lines of a text file
  • Combining template files with the Linux Cat command
  • Merging split files with the Linux Cat command
  • Combining data streams with the Linux Cat command
  • When not to use the Linux Cat command?
  • What are alternatives to the Linux Cat command?
  • What commands are similar to Linux cat?
  • 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).

    Tip

    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:

    1. Short form: -, 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.

    2. Long form: –, 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:

    OptionExplanation-h, –helpShow Linux Cat command help-nNumber lines of the output-sCombine several blank lines into one-bNumber all lines of the output except for blank lines-vOutput invisible characters-eLike -v, including end-of-line marker-tLike -v, including tab marker-etCombination of -e and -t; output all invisible charactersWhat 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”:

    OperatorLanguage(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, 67How 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:

    RedirectionSymbolUseExplanationPipecmd1 cmd2Forward output of command cmd1 to input of command cmd2Input redirect<cmd < dataInput to command cmd read from file dataOutput redirect>cmd > dataWrite the output of the cmd command to the data file; if necessary, the existing file will be overwritten.Output redirect>>cmd >> dataWrite 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:

    Linux command

    Explanation

    split

    Split a file into pieces; operation can be reversed with Cat

    uniq

    Remove lines of input that occur more than once

    sort

    Sort lines of the input alphanumerically

    head, tail

    Limit output to lines at beginning/end

    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 &gt; 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.txtWriting 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.txtsimpsons-2.txtsimpsons-3.txtLisa Bart BartMargeLisaMaggieHomerHomerNelsonFlandersMilhouse

    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.txtUsing 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.txtCombining 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

    By admin

    Leave a Reply

    Your email address will not be published.