top | item 24640552

(no title)

jfhufl | 5 years ago

I get a lot of mileage out of

    command | ruby -e 'ARGF.each { |line| #do stuff with line }'

discuss

order

3pt14159|5 years ago

Same, but I was doing it so often I made an alias to a script in my dotfiles folder.

   ruby_code = ARGV[0]

    loop do
      line = $stdin.gets()
      l = line
      break unless line
      line.chomp!
      final_ruby_code = 'puts "' + ruby_code + '"'
      eval(final_ruby_code, binding())
    end
Invoked like this:

    echo foo | rg "The double do: #{l * 2}"
To print:

   The double do: foofoo
Extremely useful when data munging around.

dorianmariefr|5 years ago

mine is called ruby-each-line:

    #!/usr/bin/env ruby

    if ARGV.size != 1
      puts "USAGE: ruby-each-line CODE"
      exit
    end

    STDIN.each_line do |line|
      line = line.strip
      l = line
      eval(ARGV.first)
    end

brigandish|5 years ago

You can cut that back a bit with the '-n' switch. Using an example from this helpful article[1] on some of the switches Ruby inherited from Perl:

    ps ax | ruby -e 'ARGF.each { |line| puts line.split.first if line =~ /top/ }'
becomes:

    ps ax | ruby -ne 'puts $_.split.first if $_ =~ /top/'
It even squashes the extra newline the ARGF version prints out first.

[1] https://robm.me.uk/ruby/2013/11/20/ruby-enp.html

asicsp|5 years ago

Well, my book linked in this post is all about using Ruby from cli, with Perl like switches.

    ps ax | ruby -ane 'puts $F[0] if /top/'