The "ruby" binary (at least MRI's) supports a lot of the switches that made perl one-liners quite popular.
Significant ones:
- -n Sets up an outer loop with just "gets" - which magically works with given filename or STDIN, setting each read line in $_
- -p Similar to -n but with an automatic `put`s at the end of each loop iteration
- -a Automatic call to .split on each input line, stored in $F
- -i In-place edit input files
- -l Automatic call to .chomp on input
- -e Execute a piece of code
- -c Check source code
- -w With warnings
Some examples:
# Print each line with its number:
ruby -ne 'print($., ": ", $_)' < /etc/irbrc
# Print each line reversed:
ruby -lne 'puts $_.reverse' < /etc/irbrc
# Print the second column from an input CSV (dumb - no balanced quote support etc):
ruby -F, -ane 'puts $F[1]' < /etc/irbrc
# Print lines that contain "eat"
ruby -ne 'puts $_ if /eat/i' < /etc/irbrc
# Same as above:
ruby -pe 'next unless /eat/i' < /etc/irbrc
# Pass-through (like cat, but with possible line-end munging):
ruby -p -e '' < /etc/irbrc
# Uppercase all input:
ruby -p -e '$_.upcase!' < /etc/irbrc
# Same as above, but actually write to the input file, and make a backup first with extension .bak - Notice that inplace edit REQUIRES input files, not an input STDIN:
ruby -i.bak -p -e '$_.upcase!' /etc/irbrc
Feel free to google "ruby one-liners" and "perl one-liners" for tons more usable and practical examples. It essentially allows you to use ruby as a fairly powerful replacement to awk and sed.