From the Canyon Edge -- :-Dustin

Thursday, August 26, 2010

Buy 1, get 8 Free! Or, a Useful Awk Hack...


But first, a couple of updates...
  1. If you appreciated my errno post, you might be happy to know that /usr/bin/errno is now provided by the ubuntu-dev-tools package in Maverick. This probably won't be the permanent home for the utility (currently in discussions with Joey Hess about putting it in moreutils, and the kernel team about putting it in linux-tools). But while we debate among ourselves about the permanent location of the bike shed, you -- our Ubuntu users -- are welcome to go about using the tool.
  2. And if you liked my bash alert post, you might also be happy to know that the alert alias is also in Maverick's skeleton .bashrc. This only affects new Maverick installs, and you'll have to install the libnotify-bin package, but still, it's a useful tool, and a good start. Several people have suggested UDS-Natty sessions on how to make the tool more universally useful, and it would be cool to see those move forward in the next cycle.
Okay, now for another fun set of tools!

All too often, I found myself typing something like this:
... | awk -F":" '{print $3}'
That's a lot of wasted characters, and it's easy to flub them up.

And so I generalized it, with this 2-line shell script in /home/kirkland/bin/1:
#!/bin/sh
[ -n "$1" ] && ifs="-F\"$1"\" || ifs=
eval awk $ifs "'{print \$$(basename $0)}'" /dev/stdin

And then I made symlinks to this one script, for numbers 2-9:
cd $HOME/bin
for i in $(seq 2 9); do
ln -s 1 $i
done

And now I can:
errno "" | 1
euca-describe-instances | 2
cat /etc/passwd | 7 :

I started out with just simple aliases for 1..9, but I found myself often needing to change the input field separator (IFS). In case you'd prefer the simple aliases, you can use these:
for i in $(seq 1 9); do
alias $i="awk '{print \$$i}'"
done

What do you think?
  • Would you like to see these as /usr/bin/1 ... /usr/bin/9 in Ubuntu Natty?
  • Do you have a more efficient implementation?

:-Dustin

p.s. My wife, Kim, took both of these pictures recently, on the side of the road in Michigan and New York, respectively. Pretty birds, hard to photograph! :-)

Printfriendly