Command line tips & tricks - concatenation with cat

  • March 27, 2007
  • Avatar for peter
    Peter
    Upfold

If you've done any sort of command line stuff on a Unix-like OS, you've probably come across cat. It stands for 'concatenate', but most often we use it to simply spit out the contents of a file, like this:

$ cat myfile

So hang on - why is it called concatenate if we're only showing the contents of one file? Well, if you give cat one file, it just does that.

As the name suggests however, you can give cat two files and it will - guess what - concatenate them together and throw them out at the end.

Like this:

$ cat fileone filetwo

There, you'll be given an output containing the contents of both files. Why is this useful? It might not seem it, but there are a number of situations where this could help you.

Say you have a couple of files, and you want to search for a particular phrase in both. You could cat them together, and grep the result for the thing you're searching for, like so:

$ cat fileone filetwo | grep 'searching for this'

This example wouldn't tell you which file the results was, but it's just a nice and simple example. How about another?

Say you have a compressed file that has been split into 600 MB chunks (for burning to CD, for example). You can download all the chunks, then cat them together (instead of sending the output to the screen, we redirect it to a finished file that you can then decompress).

$ cat part1 part2 part3 part4 > completefile

Finally, here's a really neat trick, and that's how to use cat as a very basic text editor. Type in the following into your terminal:

$ cat > newfile

After hitting enter to run the command, type in some text you want to save into the new file. When you're done, press Ctrl-D and cat will write that text to the file. Neat, huh?

Have you got an awesome tip or trick you want to share with FOSSwire readers? It could be anything, provided that it's got something to do with free and open source software. Email them to peter at gizbuzz .co dot uk!

Avatar for peter Peter Upfold

Home » Articles »