The Cat Command in Linux – Concatenation Explained with Bash Examples

The cat command is one of the most frequently used commands in Linux, with a history going back to the early days of Unix. Short for "concatenate", cat is a versatile utility that can create, combine and print the contents of files. Whether you‘re new to Linux or an experienced user, mastering cat is a fundamental skill for any aspiring command line guru.

In this guide, we‘ll start with the basics of using cat, then progress to more advanced examples involving pipes, redirection, and other common Linux commands. We‘ll also compare cat to similar tools and discuss when you might want to use other options. But first, let‘s break down the name "concatenate" to understand what cat really does.

What is Concatenation?

Concatenation is a fancy word meaning "to link together in a series or chain". When you concatenate something, you join pieces together end-to-end, like cars on a train or paper clips hooked onto each other.

In programming, concatenation usually refers to joining two or more strings (text) together. For example, the strings "hello" and "world" could be concatenated to form "helloworld". Many programming languages use the + operator for concatenation, like:

str1 = "hello"
str2 = "world"
result = str1 + str2
print(result) # "helloworld"

The cat command in Linux performs a similar function, but with files instead of strings. When you cat file1 and file2 together, their contents get joined into one longer text stream. It‘s like laying transparencies on top of each other on an overhead projector – you see the combined contents as if they were one document.

So in summary:

  • Concatenation = linking pieces together in a chain
  • The cat command concatenates the contents of files

Equipped with this background knowledge, let‘s dive into some hands-on examples of using cat.

Basic Cat Usage

The most basic form of the cat command takes one or more files as arguments and prints their contents to the terminal (stdout). The syntax looks like this:

cat file1.txt file2.txt

This will display the combined contents of file1.txt and file2.txt, as if they were one file. But before we can concatenate files, we need some files to work with. Fortunately, cat can help with that too.

Creating Files with Cat

Besides displaying files, cat can also create them. The easiest way is to use the output redirection operator > with cat and no arguments, like this:

cat > sample.txt

Whatever you type next will go into sample.txt, until you press Ctrl-D to save and exit. This is faster than opening a text editor for quick notes or test files.

You can also create a file "on the fly" by piping or redirecting text into cat:

echo "Hello World" | cat > hello.txt

Now hello.txt contains the string "Hello World". We‘ll cover more redirection examples later.

Viewing File Contents

To view the contents of a file with cat, simply pass the filename as an argument:

cat hello.txt

This prints "Hello World" to the terminal. You can view multiple files at once by listing them all:

cat file1.txt file2.txt file3.txt

Cat will concatenate all the files and print them to stdout as one text stream. This is where the command gets its name!

Combining Files

Viewing concatenated files is fine, but what if you want to save the result? You could copy and paste the text, but that‘s tedious. A better way is to redirect cat‘s output to a new file, like this:

cat file1.txt file2.txt > combined.txt

Now combined.txt contains the concatenated contents of file1.txt and file2.txt. Easy, right? But what if combined.txt already exists? Then you have two options:

  1. Overwrite combined.txt with the > operator (be careful!)
  2. Append to the end of combined.txt with the >> operator

Here‘s what appending looks like:

cat file3.txt >> combined.txt

Now combined.txt contains file1, file2, and file3 all smushed together. You can keep appending more files, or use this technique to add lines to the end of an existing file. For example:

echo "Goodbye World" >> combined.txt

Will tack the string "Goodbye World" onto a new line at the end of combined.txt.

Using Cat with Other Commands

Like most Linux utilities, cat becomes even more powerful when combined with other commands through pipes and redirection. Let‘s explore some common combos.

Pipes

The | character, called a "pipe", lets you feed the output of one command into the input of another. For example, you could pipe cat into grep to search for a string in a file:

cat file.txt | grep "hello"

This will print any lines in file.txt that contain the string "hello". Grep is a super useful tool – check out our grep tutorial to learn more.

You can chain multiple commands together with pipes. Here‘s an example that uses cat, grep, and wc (word count) to count how many lines contain "hello":

cat file.txt | grep "hello" | wc -l

Pipes are an essential part of the Unix philosophy of small, focused tools that work together.

Redirection

We‘ve already seen basic output redirection with > and >>. You can redirect stdout to a file, or even redirect it to another command with |. But you can also redirect stdin (standard input) from a file into a command using the < operator.

For example, instead of catting a file and piping it to grep, you could redirect the file into grep directly:

grep "hello" < file.txt  

This has the same effect as cat file.txt | grep "hello". In fact, many commands that accept stdin let you specify a filename directly, making the explicit redirection unnecessary:

grep "hello" file.txt

This works with cat too, but cat without a filename argument just copies stdin to stdout, so it‘s not very useful on its own. Where stdin redirection shines is when combining multiple commands. For instance, you could redirect a file into a while loop that reads each line and does something with it:

while read line; do
  echo "Processing: $line"
done < file.txt

Here, the contents of file.txt are fed into the while loop one line at a time. This is a common pattern for shell scripting.

Advanced Cat Tricks

By now, you should have a solid grasp of basic cat usage. But cat has a few more tricks up its sleeve that are worth knowing.

Line Numbers

The -n option prints line numbers before each line:

cat -n file.txt

This is handy for referring to specific lines or tracking down errors. The -b option is similar, but only numbers non-blank lines. This can be useful for source code or data files where blank lines are ignored.

Special Characters

Normally, cat just spits out the literal contents of a file, but sometimes you want to see special characters like tabs, line endings, and other non-printing characters. The -A flag (show all) displays these as escape sequences:

cat -A file.txt

Now tabs show up as ^I, line endings as $, and other special characters have their own codes. This can help diagnose problems with formatting or corrupt files.

Squeezing Blanks

If a file has a lot of blank lines, cat‘s -s option (squeeze) replaces multiple adjacent blank lines with a single blank line:

cat -s file.txt   

This can make the output more readable without changing the contents of the file itself.

Cat Alternatives

For all its versatility, cat isn‘t always the best tool for the job. Here are some alternative commands to consider.

Less is More

If you‘re viewing a long file, catting it all at once can flood your terminal with text. The less command is a better choice for navigating lengthy output:

less file.txt

Less displays one screenful of text at a time, and lets you scroll up and down with the arrow keys or page with the spacebar. Press q to quit. Learn more in our less command tutorial.

Just the Beginning or End

Sometimes you only need to see the first or last few lines of a file. For this, use the head and tail commands:

head -n 5 file.txt  # first 5 lines
tail -n 3 file.txt  # last 3 lines 

You can even combine them to extract a range of lines:

cat file.txt | head -n 20 | tail -n 10  # lines 11-20

Editing Files

While cat can create and concatenate files, it‘s not an editor. For that, you‘ll want a proper text editor like nano, vi, or emacs. These let you interactively edit files with features like search and replace, copy/paste, and undo.

That said, you can still make small edits to files with cat and shell redirections. For example, to uppercase the contents of a file:

cat file.txt | tr a-z A-Z > loud_file.txt

Or to search and replace a string:

cat file.txt | sed ‘s/cat/dog/g‘ > dogfile.txt

But for anything more than trivial edits, bust out a real editor. They‘re not as scary as you might think – try our vim or emacs tutorials to get started.

Conclusion

We‘ve covered a lot of ground in this tutorial, from the basic structure of the cat command to advanced techniques with pipes and redirection. Cat may seem simple, but it‘s a core part of the Linux toolbox with a surprising depth of functionality.

To recap, here are the key tasks we learned to do with cat:

  • Create files by redirecting stdin
  • View one or more files
  • Concatenate files together
  • Add line numbers or special characters
  • Combine cat with other commands using pipes and redirection

I hope this guide has given you a solid foundation for working with cat and text in the Linux terminal. Of course, there‘s always more to learn. I encourage you to read the cat man page (man cat) and experiment with different options and combinations.

As you progress on your Linux journey, you‘ll find yourself using cat almost every day, along with its trusty companions grep, sed, awk, and others. These tools embody the Unix philosophy of doing one thing well. Mastering them will make you a power user in no time!

Happy catting! 🐱

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *