假设我在终端中输入了一些内容,例如:
ls | grep phrase
这样做之后,我意识到我想删除所有这些文件。
我想使用 Ruby 来做到这一点,但不能完全弄清楚要传递给它的内容。
ls | grep phrase | ruby -e "what do I put in here to go through each line by line?"
假设我在终端中输入了一些内容,例如:
ls | grep phrase
这样做之后,我意识到我想删除所有这些文件。
我想使用 Ruby 来做到这一点,但不能完全弄清楚要传递给它的内容。
ls | grep phrase | ruby -e "what do I put in here to go through each line by line?"
以此为起点:
ls ~ | ruby -ne 'print $_ if $_[/^D/]'
返回:
Desktop
Documents
Downloads
Dropbox
该-n
标志表示“遍历所有传入行”并将它们存储在“默认”变量$_
中。我们没有看到这个变量被大量使用,部分原因是对 Perl 过度使用它的下意识反应,但它在 Rubydom 中有它有用的时刻。
这些是常用的标志:
-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
ARGF
会保存你的培根。
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
是一个数组,用于存储您传递到(在本例中为命令行)脚本中的任何内容。您可以在此处阅读更多信息ARGF
:
http://www.ruby-doc.org/core-1.9.3/ARGF.html
有关更多用途,请查看 Ruby 论坛上的演讲: http ://www.ruby-forum.com/topic/85528