June 09, 2010, 4:47 PM — Not every Unix command sparks with novelty. After all, the OS has now been around for roughly forty years and the spark wears off. But there are some commands that pick up from where the basics run out of steam. Jump on a Linux box and try these out when you have a little free time. You might surprise yourself with some new tricks for your bag of Unix goodies.
Before we get started with the commands you may not have heard of before, here's a tired and true Unix command that we've all been using for decades, but maybe not this particular way. This grep command represents the simplest way to remove blanks lines from a file that I've ever seen.
grep . oldfile > newfile
Got that? It matches any lines with anything (i.e., not nothing) in them and tosses them into the second file. Hey, this is even easier than my old "grep -v ^$ oldfile > newfile" command that would specifically omit empty lines from the new file.
Now let's look at a command you might not have come across before. The comm command (think of "comm" as in "common" to be contrasted with "diff" as in "difference"). The comm command will attempt to display the lines that two files have in common. Here's an example:
$ cat file1 Remember when we were poor? No. Me neither. The end. $ cat file2 Let's slip a coin! Flip what? The end. $ comm file1 file2 Let's slip a coin! Flip what? Remember when we were poor? No. Me neither. The end.
Pay attention to the way the output is indexed. The lines up against the left side of your screen are those that appear only in the first file. The lines in the middle column appear only in the second file. The lines in the rightmost column are those that appear in both files. In similar manner to diff, the ordering of the lines makes a big difference in how the command operates. If the files aren't sorted, comm will only find the first set of matching lines. Any additional matches will be ignored. Let's look at another example and see this in practice.
Let's say we have a file containing the letters a, b, c, x, a, b, c (one per line) and another containiny a, b, c, x, a, b, c. The comm command will only detect the first match.
$ comm file5 file6 a b c f a b c x a b c
Like diff, the comm commands has some other options (like selecting whether to see only some of this output). Read the man page.
Another interesting command is called "tac". Yes, that's "cat" spelled backwards. And what would you expect such a command to do? It displays a file in reverse order -- upside down. So, our a, b, c, x, a, b, c file shows as:
$ tac myfile c b a x c b a
Another interesting command is called "links", homonym for "lynx" and a command with a similar purpose in life.