Bash Commands - But In Ruby!

Bash Commands - But In Ruby!

Ruby Developer - Essential Bash Commands, Ruby Edition

Ziemek wrote an amazing post about essential bash commands for Ruby developers over at his blog.  I thought it would be fun to show some of the same commands, but using command line Ruby instead. I find using Ruby with the -ne flag easier to remember and easier to expand in to more complex scripts.

This is not a hammer vs screwdriver kind of argument... more of a composite handle hammer vs a wooden handle hammer. Without further ado, I'm going to show you how to use Ruby instead of the awk / grep / sed combo going example by example to transform each of Ziemek's fantastic Bash examples in to Ruby ones.



The Basics

These are the building blocks we'll need later on to do the more complex examples.


To get all the subdirectories inside a directory the grep command is

ls -l | grep drw

And here is the same in Ruby

ls -l | ruby -ne 'print if /drw/'

This is clearly not more terse, but our powers are not as limited.


Get just the sizes of the ls

ls -l | awk '{print $5}'

And in Ruby

ls -l | ruby -ne 'puts $\_.split(/\s+/)[4]'

Now we know enough to start making things more efficient. Let's put those two together and get the size of only the directories

ls -l | grep drw | awk '{print $5}'

and Ruby time

ls -l | ruby -ne 'puts $\_.split(/\s+/).last if /drw/'

We only process the list one time in Ruby instead of twice in the grep + awk example


Remove log-file- from names if they exists
ls -l | sed -e "s/log-file-//"


ls -l | ruby -pe 'gsub(/log-file-/) {$1}'

Ok, so now we have our tools, let's get to the main event.

Here are the sample files for the log filing example:

Sample files used

Commands used in the video above:

ls -1 | grep "log-file" | sed -e "s/log-file-//" | sed -e "s/-..\.log//" | uniq | awk
'{print "mkdir "$1}' |bash
ls -la | grep drw
ls -1 | grep "log-file"| awk -F'-' '{print "mv "$0" "$3"-"$4}' | bash

and here are the Ruby versions

ls -1 | ruby -ne 'puts "mkdir " + gsub(/(log-file-|-..\.log)/, "") if /log-file/' | uniq | bash
ls -la | ruby -ne 'print if /drw/'
ls -1 | ruby -ne 'puts "mv #{$_.strip} #{$_.split(/-/)[2]}-#{$_.split(/-/)[3]}" if /log-file/' | bash

Dump all your postgres tables

psql -ls | grep rob | awk '{print "echo "$1" && pg_dump "$1" -f "$1".sql"}'

psql -ls | ruby -ne '(name=$\_.split(/\s+/)[1]; puts "echo #{name} && pg_dump #{name} -f #{name}.sql") if /rob/'

I hope you enjoyed this foray in to translating grep, awk and sed commands in to Ruby. I imagine these one liners can be simplified, if so , please let me know in the comments and thanks again to Ziemek for the inspiration to this article.
Rob Kaufman
Rob Kaufman