Monday, February 23, 2009

Fun application of tr

Lately youtube has been shutting down utilities that let you download videos easily.

So, what I've been doing is using the LiveHTTPHeaders plugin to Firefox to just copy out whatever .flv file it's requesting. However, this always copies out an extra line break which messes up the shell.

To filter out line breaks from the clipboard (OS X only):

pbpaste | tr -d '\n' | pbcopy

Friday, February 20, 2009

Wednesday, February 18, 2009

XOR swap algorithm

There is a way to swap two variables without needing a swap variable. It's called the XOR swap algorithm.

X := X XOR Y
Y := X XOR Y
X := X XOR Y

This allows you to swap two columns in a table if you can't alter the table to add a column temporarily to swap them. I'm not sure how mysql handles user variables in update statements.

Shell braces

most shells with expand braces with commas, like so:

$ echo file{1,2,a}
file1 file2 filea

You can even nest them:

$ echo file{1,2,3{1,2}}
file1 file2 file31 file32

There are several cool uses for this trick.

The first to copy a file to itself plus .bak:

cp /path/to/somefile{,.bak}

You can also combine this with backtick to version a file with a date:

cp /path/to/somefile{,-`date -I`}

Tuesday, February 17, 2009

ssh-copy-id

If you use ssh keys to achieve a higher level of security (or more likely, achieve passwordless logins), you are used to having to copy your public key from one server to another, very likely using some completely insecure method.

use instead ssh-copy-id, which will prompt you to log in to the remote machine one last time using your existing login and will copy your public key into the correct file securely using ssh.

bulk rename utility

There is a bulk rename utility which is installed by default in many distributions calls 'rename'. It expects a perl regular expression to describe the substitution.

You can use this to, say, change the file extension of several files:

rename 's/\.htm$/.html/' *.html

It's written in perl and was originally written by Larry Wall.

Monday, February 16, 2009

Disposable variables

Ever have a bunch of variables you get returned in a tuple, and you only want some of them? So you assign them to some useless variable like 'nothing' or 'deleteme' and hope that the optimizer will instantly garbage collect them away?

(user, user_type, ingorethis) = somefunction()

The correct way to do this is to use the _ variable. (underscore). Underscore is equivalent to perl's $_ variable: it contains the results of the last evaluated expression. This is sometimes useful if you're using the python shell as a calculator. So, it will instantly be overwritten.

(user, user_type, _) = somefunction()

Thursday, February 5, 2009

Do a mysqldump on a limited number of records

To limit a mysqldump to dump only N records:

mysqldump --where 'true limit N'