Combining Multiple Files
The cat
command can also be used to combine multiple files. This is where the "concatenate" part of its name comes from.
- First, let's view the contents of both
sales.txt
and marketing.txt
separately:
cat sales.txt
cat marketing.txt
Take note of the contents of each file.
- Now, let's combine these files:
cat sales.txt marketing.txt
This command will display the contents of both files, one after the other, as if they were a single file. Notice how cat
simply outputs the contents of each file in the order you specify.
- Now we're going to introduce a new concept called "output redirection". In Linux, we can take the output of a command (what you normally see printed in the terminal) and send it to a file instead. We do this using the
>
symbol. Here's how it works:
cat sales.txt marketing.txt > combined_report.txt
Let's break this down:
cat sales.txt marketing.txt
is the command we've used before to display the contents of both files.
- The
>
symbol is new. It tells Linux to take whatever would have been displayed in the terminal and instead write it to a file.
combined_report.txt
is the name of the new file we're creating.
So, this command is saying: "Take the combined contents of sales.txt and marketing.txt, and instead of showing them to me, put them in a new file called combined_report.txt."
This is a powerful feature in Linux that allows you to save the output of commands for later use. Don't worry if it seems a bit confusing at first - you'll get plenty of practice with it in future lessons.
- To make sure our redirection worked, let's verify the contents of the new file:
cat combined_report.txt
You should see the contents of both sales.txt
and marketing.txt
in this new file. If you do, congratulations! You've successfully used output redirection to combine files.