Thursday, September 07, 2006

Ruby Oneliners

Ruby can be very useful for performing some rapid and powerful operations on files. The Ruby syntax is much more user friendly than awk or sed, especially if you are familiar with Ruby.
The one liners can be found here.
If you are running on Windows, then substitute type for cat.
As an example, Here is a handy oneliner

# delete leading whitespace (spaces/tabs/etc) from beginning of each line
$ cat | ruby -pe 'gsub(/^\s+/, "")'

Note that the command
ruby -pe
will execute the Ruby commands that follow it on each input line, and sends the output to STDOUT. To capture the output you can use the Linux/Unix or DOS > char.
Another useful oneliner is the following:

# print line number 52
$ cat | ruby -pe 'next unless $. == 52'

The above oneliners depend on the $ Ruby global variables. Here are some of the most commonly used:

$! error message
$@ position of an error occurrence
$_ latest read string by `gets'
$. latest read number of line by interpreter
$& latest matched string by the regexep.
$1, $2... latest matched string by nth parentheses of regexp.
$~ data for latest match for regexp
$= whether or not case-sensitive in string matching
$/ input record separator
$\ output record separator
$0 the name of the ruby script file
$* command line arguments for the ruby script
$$ PID for ruby interpreter
$? status of the latest executed child process

Have fun.

No comments:

Just Google it!