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.
grep
To get all the subdirectories inside a directory the grep command is
And here is the same in Ruby
This is clearly not more terse, but our powers are not as limited.
awk
Get just the sizes of the ls
And in Ruby
Now we know enough to start making things more efficient. Let's put those two together and get the size of only the directories
and Ruby time
We only process the list one time in Ruby instead of twice in the grep + awk example
sed
Remove log-file- from names if they existsRuby
Ok, so now we have our tools, let's get to the main event.
Here are the sample files for the log filing example:
Commands used in the video above:
'{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 -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
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.