Posted By

myjpa on 08/05/08


Tagged

shell-tool


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

webstic


do sth. on eachline from STDIN


 / Published in: Ruby
 

This script is intended to use after the pipe '|' on unix shell. It execute a one-line ruby code(you can split multi-line ruby-code with ';', of course) iteratively on each-line from the STDIN, each-line of which is assigned to a variable x.

eg. ls | eachline.rb '$no||=1;puts "#$no - #{x}";$no+=1' the output looks like this: 1 - README.image 2 - README.image~ 3 - bin 4 - boot ...

Simple enough, isn't it?

  1. #!/usr/bin/env ruby
  2. #supress any warning when calling other shell commands.
  3. $VERBOSE = nil
  4.  
  5. def die(msg)
  6. puts msg
  7. exit 1
  8. end
  9.  
  10. $cmd = ARGV.shift
  11. die "you should specify a string of ruby code to deal with eachline of STDIN" unless $cmd
  12.  
  13. $in = STDIN.readlines
  14. $in.each do |x|
  15. x.chomp!
  16. eval($cmd)
  17. end

Report this snippet  

You need to login to post a comment.