life.i.think: f.rb: An awk script.

f.rb: An awk script.
Scribbled on July 12th. 5 comments.

Also known as “the most the most useful piece of software [someone else] wrote in [a] calendar year,” rewritten.

Today Mark Dominus blogged about f, a wholly fantastic and tiny Perl script that changes:

ps aux | awk ‘{print $2}’ to ps aux | f 2.

Of course there’s the deeply embedded urge of every geek to take something like this and reproduce it in all possible languages (plus there was a syntax error running the Perl script on my end), so here we have it in Ruby!


#!/usr/bin/ruby

($stderr.print "f.rb usage: fieldnumber\n"; exit) if ARGV.empty?
$stdin.each { |l| puts l.split[ARGV.first.to_i-1] }

Download.

Comments

Leave a response

  1. Ian McKellarJuly 12, 2007 @ 11:45 PM

    What’s wrong with cut -f?

  2. BrittJuly 13, 2007 @ 01:42 AM

    cut -f only works for tabs, where as something like ps outputs spaces.

  3. BenJuly 13, 2007 @ 02:31 AM

    If you know exactly in what column your data lies, you could use the -b ‘bytes’ specifier for cut. Or if you know how many spaces, you can change the delimiter cut uses with the -d option. I find myself using “cut -d’ ’ ...” often.

  4. evanJuly 13, 2007 @ 04:00 PM

    I usually only care about column 2, so an alias in ~/.bash_profile is even simpler:

    alias 2nd=”awk ‘{print \$2}’”

  5. topfunkyJuly 13, 2007 @ 07:24 PM

    Nice! I named it ‘nth’ and put it in my ~/bin directory.