Main Content

One line scripts - Awk, Perl and Ruby

Archive - Originally posted on "The Horse's Mouth" - 2016-05-20 08:12:31 - Graham Ellis

The art of the one line script, originating in awk and passing through Perl lives on in Ruby!

  WomanWithCat:4c grahamellis$ awk '/Upper/{c++}; END { print(c,"of",NR)}; BEGIN {c=0}' rstats2015.txt
  5 of 2537
  WomanWithCat:4c grahamellis$


  WomanWithCat:4c grahamellis$ perl -n -e '$c++ if /Upper/; END { print("$c of $.\n")}; BEGIN {$c=0}' rstats2015.txt
  5 of 2537
  WomanWithCat:4c grahamellis$


  WomanWithCat:4c grahamellis$ ruby -n -e 'c += 1 if /Upper/; END { puts "#{c} of #{$.}"}; BEGIN {c=0}' rstats2015.txt
  5 of 2537
  WomanWithCat:4c grahamellis$


I'm not a great one to encourage short scripts like this in general use ... but as a teaching exercise they're interesting in showing the flexibility of the language, and occasioanally used in a shell script, they can save the whole script having to be moved to another language just because of one analysis / calculation needed.