Sunday, November 26, 2006

Ruby: one liners

Sometimes it is necessary to do some simple things, like replacing some words in given file, processing output of the Unix command. To such operation, usually writing a Ruby script is just unnecessary, due to possibility of creating one line so-called one liners programs, short script as Ruby command-line option: -e 'command' and -n , where:
  • -e 'command' - Executes command as one line of Ruby source. Several e’s are allowed, and the commands are treated as multiple lines in the same program. If programfile is omitted when e is present, execution stops after the e commands have been run. Programs 1.8 run using e have access to the old behavior of ranges and regular expressions in conditions—ranges of integers compare against the current input line number, and regular expressions match against $_.
  • -n - Assumes a while gets; ...; end loop around your program.

For example simple grep program can be implemented in Ruby as:

ruby -n- e "print if /blabla/" *.txt


Or, for instance, if one wants to save a list of all *.tif, *.TIF, *.tiff, *.TIFF files in given directory in lowercase:

ls -l | ruby -n -e ' puts split[8].downcase if $_.to_s.upcase =~/TIFF?/' > list.txt

Of course, those examples can be done without the need of Ruby, just by using standard Unix command, but sometimes it is easer to use e.g. Ruby (the same thing can be done using Perl, Python, awk,...) than to look for syntax of a given command. If one is familiar with e.g. Ruby, few separate Unix commands can be done in one Ruby command-line program.

Many other handy examples of ruby one liners can be found here.

No comments:

Post a Comment