Tuesday, December 16, 2008

Ruby

Ruby is a popular text processing language that has gained a lot of momentum over the last few years, mostly due to the rise of Ruby on Rails. It has a lot of the good things from Perl, but implements a fully object oriented model and syntax.

Ruby is part of the default install of OS X.

Working with Ruby gems

Gems are Ruby packages that can be installed to extend the language or provide additional functions. Gems are managed using the gem command. To find all Ruby gems (packages) currently installed:

gem list

To install a new gem:

gem install package

To update the gems package manager:

update_rubygems

Taint mode

For untrusted scripts, add -T flag to ruby at the start of the script:

#!/usr/bin/ruby -T

One liner to edit a file in place

This command edits a file in place, performing a global text search/replace. The -p switch tells ruby to place your code in the loop while gets; ...; print; end. The -i tells ruby to edit files in place, and -e indicates that a one line program follows.

ruby -p -i -e '$_.gsub!(/248/,"949")' file.txt

One liner to remove DOS line endings from a file

A Unix or Mac text file uses a single line feed character to mark the end of a line (hex 0A). Files created on DOS or Windows use two characters, carriage return and line feed (hex 0D 0A). This command edits a file in place, removing the carriage returns.

ruby -p -i -e '$_.gsub!(/\x0D/,"")' file.txt

One liner to edit files in place and backup each one to *.old

ruby -p -i.old -e '$_.gsub!(/248/,"949")' *.txt