Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you pipe shell output to ruby -e?

Tags:

ruby

Say I was typing something in my terminal like:

ls | grep phrase

and after doing so I realize I want to delete all these files.

I want to use Ruby to do so, but can't quite figure out what to pass into it.

ls | grep phrase | ruby -e "what do I put in here to go through each line by line?"
like image 575
ovatsug25 Avatar asked Jan 05 '13 22:01

ovatsug25


People also ask

What is the pipe operator in Ruby?

The pipeline operator is used to provide the output of the left side to the input of the right side. It explicitly requires that this be the sole argument to the function, of which can be circumvented with currying techniques in both languages to partially apply functions.

How do I run Ruby shell?

You can start it by typing irb in your shell and hitting enter. Its name is short for “Interactive Ruby Shell”, and yes, it is another kind of shell: Just like the shell running in your terminal irb is also a program that interactively waits for you to type something, and hit enter.


2 Answers

Use this as a starting point:

ls ~ | ruby -ne 'print $_ if $_[/^D/]'

Which returns:

Desktop
Documents
Downloads
Dropbox

The -n flag means "loop over all incoming lines" and stores them in the "default" variable $_. We don't see that variable used much, partly as a knee-jerk reaction to Perl's overuse of it, but it has its useful moments in Rubydom.

These are the commonly used flags:

-e 'command'    one line of script. Several -e's allowed. Omit [programfile]
-n              assume 'while gets(); ... end' loop around your script
-p              assume loop like -n but print line also like sed
like image 107
the Tin Man Avatar answered Oct 14 '22 07:10

the Tin Man


ARGF will save your bacon.

ls | grep phrase | ruby -e "ARGF.read.each_line { |file| puts file }"
=> phrase_file
   file_phrase
   stuff_in_front_of_phrase
   phrase_stuff_behind

ARGF is an array that stores whatever you passed into your (in this case command-line) script. You can read more about ARGF here:

http://www.ruby-doc.org/core-1.9.3/ARGF.html

For more uses check out this talk on Ruby Forum: http://www.ruby-forum.com/topic/85528

like image 21
ovatsug25 Avatar answered Oct 14 '22 08:10

ovatsug25