Using Ruby as an AWK replacement
Someone at work asked if you could use Ruby like AWK. I did a little digging and found that you can.
cat file | ruby -n -a -e 'puts "#{$F[0] $F[1]}"'
‘-n’ makes the Ruby iterate over all lines successively assigning them to $_
‘-a’ makes Ruby split $_ into its parts assigning the result to $F which is an array of strings
‘-e’ means that what follows is code to be executed.
‘-F’ specifies the column separator
I performed a speed comparison on some different size files and operations. For files under 500kb lines Ruby has comparable performance to AWK. For anything larger then Ruby (1.8.6) is at best twice as slow. Though I wouldn’t expect a general purpose language to outperform a specialist tool.
Subscribe to the RSS feed and have all new posts delivered straight to you.
Thanks, Joe, that’s really interesting. Just another choice in the myriad of options we have!
Cheers John. A colleague at work was bemoaning AWK so I thought this would be useful.
We can name that rawk.
BTW, I would not expect ruby outperform any tool.
in fact, perl was invented as a more powerful awk, and ruby inherits a lot from perl, so it’s not surprising to achieve it with ruby.