Skip to content

Instantly share code, notes, and snippets.

@maxidr
Created November 12, 2012 11:49
Show Gist options
  • Save maxidr/4058929 to your computer and use it in GitHub Desktop.
Save maxidr/4058929 to your computer and use it in GitHub Desktop.
Ruby as AWK
# ruby -n option: Causes Ruby to assume the following loop around your script, which makes it iterate over file name
# arguments somewhat like sed -n or awk.
#
# Example:
curl -s http://www.gutenberg.org/files/1080/1080.txt |
ruby -ne '
BEGIN { $words = Hash.new(0) }
$_.split(/[^a-zA-Z]+/).each { |word| $words[word.downcase] += 1 }
END {
$words.each { |word, i| printf "%3d %s\n", i, word }
}
' |
sort -rn
# from http://tomayko.com/writings/awkward-ruby
@maxidr
Copy link
Author

maxidr commented Nov 12, 2012

and the -p option: Acts mostly same as -n switch, but print the value of variable $_ at the each end of the loop.
For example:

% echo matz | ruby -p -e '$_.tr! "a-z", "A-Z"'
MATZ

or

% echo matz | ruby -p -e '$_.upcase!'
MATZ

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment