bash 如何在命令行上通过管道输入 ruby​​ -e?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17096935/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:41:09  来源:igfitidea点击:

How to get piped input to ruby -e on command line?

rubybashpipestdin

提问by pixelearth

I'm trying to figure out how to write one liners on the bash console and pipe to ruby but I can't figure out how to get the input. This isn't working:

我试图弄清楚如何在 bash 控制台上编写一个衬垫并通过管道连接到 ruby​​,但我无法弄清楚如何获取输入。这不起作用:

echo "My String" | ruby -e "#{STDIN.read.first.downcase}"

How can I get the piped input in ruby?

如何在 ruby​​ 中获取管道输入?

回答by Stefan

Ruby treats your line as a comment because it starts with a #.

Ruby 将您的行视为注释,因为它以#.

This would work:

这会起作用:

echo "My String" | ruby -e "puts gets.downcase"

Output:

输出:

my string

I've used Kernel#getsinstead of STDIN.gets:

我用过Kernel#gets而不是STDIN.gets

Returns (and assigns to $_) the next line from the list of files in ARGV (or $*), or from standard input if no files are present on the command line

从 ARGV(或 $*)中的文件列表中返回(并分配给 $_)下一行,如果命令行上没有文件,则从标准输入返回(并分配给 $_)

If you want to process each line, you could use the -pflag. It's like wrapping your script in a while gets(); ... end; puts $_block. Ruby reads each input line into $_, evaluates your script and outputs $_afterwards:

如果你想处理每一行,你可以使用-p标志。这就像将您的脚本包装在一个while gets(); ... end; puts $_块中。Ruby 将每个输入行读入$_,然后评估您的脚本并输出$_

echo "Foo\nBar\nBaz" | ruby -pe '$_.downcase!'

Output:

输出:

foo
bar
baz

回答by Jerome Dalbert

Just

只是

echo "My String" | ruby -ne 'puts $_.downcase'

or

或者

echo "My String" | ruby -e "puts gets.downcase"

You get the idea.

你明白了。

回答by Dorian

Examples:

例子:

Strip all lines from extra spaces:

从多余的空格中去除所有行:

ls | ruby -e "STDIN.each_line.to_a.map(&:strip).each(&method(:puts))"

Randomly colorize each line:

随机为每一行着色:

ls | ruby -e "require 'colorize'; STDIN.each_line { |l| print l.colorize(String.colors.sample) }"

Sort lines by length:

按长度对行进行排序:

ls | ruby -e "puts STDIN.each_line.to_a.sort_by(&:size).reverse"

Sort files by file size:

按文件大小对文件进行排序:

ls -l | ruby -e 'STDIN.first; puts STDIN.each_line.to_a.map { |l| [l.split[4].to_i, l.split[8]] }.sort_by(&:first).reverse.map { |l| l.join("\t") }'

etc. etc.

等等等等