Thursday, January 10, 2008

Some Handy Commands

I've learned a few handy commands this year, so here's the wealth.

Sets have always been a big hole in my command line toolkit. I've gone to such lengths as to implement commands for basic set intersection and union in Perl or Python. Go no farther! While looking over Lasermacaroni's shoulder about a year ago, I noticed that he used the comm command. comm operates on sorted unique streams of lines and produces a three column output of which elements were in column A only, column B only, or both. Of course, three columns are nearly useless, so you can tell comm to suppress the output of certain columns. Yes, this is stupid, but here's your mnemonic: ask not what columns comm can display for you, rather ask what columns you can suppress from comm. Go!

A & B: comm -12 A B
A & !B: comm -23 A B
!A & B: comm -13 A B
A | B: cat A B | sort | uniq

Of course, I like to use comm like grep or grep -v to find the elements from an input stream that either are or are not in a given file. Mind that your file needs to be sorted and uniqued.

also in A:  ... | sort | uniq | comm -12 - A
not in A:   ... | sort | uniq | comm -23 - A

I've known about the seq command in Linux-land for a while. It creates lists of numbers in a given range.

seq last
seq first last
seq first stride last

For examples:

$ seq 3
1
2
3
$ seq 3 5
3
4
5
$ seq 0 2 4
0
2
4

I was quite disappointed not to find seq on Mac OS X. Turns out the BSD folks have a pretty bad case of NIH. Instead of the seq function, you may, having the good fortune of working around brilliant people every day, notice a friend, coworker, or other friendly mammal use the jot command to produce their streams of numbers.

jot [reps [begin [end [stride]]]]

Here are some occlusive examples:

$ jot 3
1
2
3
$ jot 3 5
5
6
7
% jot 3 0 6
0
3
6
% jot 3 1 1
1
1
1
jot -b+ -s- 40
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

fin

No comments: