Learning the Commandline – Looking at files

By now you should know your way around the file system and how to move around (if you don’t, go back and read the other articles. This is a series after all 🙂 ). You may have wondered, “I have all these files, how do I see what’s inside them in Terminal?” There’s an app for that (sorry, couldn’t resist). Enter the cat command and it’s helpers. We’re also going to learn what a pipe is.

cat is *nix for catalog, as in a listing of what’s in a file. ANY file. This includes binaries (executable files), although you may not get much information from them.

Lets go to /usr/share/calendar. Now type:

cat calendar.holiday

Bunch of text just flew up the screen. No one can read that fast. Lets use another command as a helper. Type:

cat calendar.holiday | more

That’s much better. To see the next page press space. When you reach the end press Q. Now lets break it down…
The cat command listed the file, normally to the screen, or terminal. In this case it is redirected to the input of the more command by a ‘pipe’ which is the | (that’s a shift-\). That’s what a pipe is, it redirects standard output of one command to standard input of another command, in this case more. The more command is a paginator, or it breaks up the output into screen sized chunks and waits for input to get the next chunk.

The problem with more is it’s only one way. You can’t back up and see something that came before. You have to start over. Enter less. It’s kind of a joke, meaning less is not more (I’m not kidding, read the man page). The less command, among other things, lets you back up in the text to see something you might have missed. Press b to back up one screen. Press space for the next one. And Q to quit. It does other things like one line at a time or n lines at a time, however you set it. See the man page for options.

Pipes are handy things to have around. Lets say you have a mailing list you need to sort, find a certain line in the list and process that line. That could take a while doing it one thing at a time. Using pipes it’s done in one command line. For example:

cat mailing.list | sort | grep (parameters) | final_processing

All one line, four different processes. I’m not going to explain sort or grep in this article, this is just an example, to show how it’s done and the power of the command line. However the logic is this: List the file, pipe the output through a sort, find a certain line or lines (or word), pipe the output of that to final processing. I’m sure you could probably find other uses for pipes. Note: not all commands support pipes. Look around on-line and find other uses of pipes.