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] }
What’s wrong with cut -f?
cut -f only works for tabs, where as something like ps outputs spaces.
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.
I usually only care about column 2, so an alias in ~/.bash_profile is even simpler:
alias 2nd=”awk ‘{print \$2}’”
Nice! I named it ‘nth’ and put it in my ~/bin directory.