【问题标题】:How do I read an input file in ruby using < in command line?如何在命令行中使用 < 在 ruby​​ 中读取输入文件?
【发布时间】:2014-03-31 16:50:17
【问题描述】:

我想让这个工作:

./search.sh < inputFile.json

./search.sh < inputFile2.json

这将根据文件输出不同的内容。然后我想这样做:

(./search.sh < inputFile.json) > results.json

我确定语法是错误的。有人能把我引向正确的方向吗?我在我的 ruby​​ 脚本中找不到如何执行此操作(我使用的是 .sh,但它是 ruby​​)。

【问题讨论】:

    标签: ruby input terminal command output


    【解决方案1】:

    您有多种选择。

    从标准输入读取

    一种选择是从标准输入读取。例如,您可以在search.sh

    #!/usr/bin/env ruby
    
    input = $stdin.read
    
    puts "here's the input i got:"
    puts input
    

    假设我们有一个文件foo.txt,看起来像这样

    foo
    bar
    baz
    

    然后你可以用一个unix管道来使用它

    ~$ ./search.sh < foo.txt
    here's the input i got:
    foo
    bar
    baz
    

    相当于

    ~$ cat foo.txt | ./search.sh
    here's the input i got:
    foo
    bar
    baz
    

    虽然这是对 cat 的无用使用,只是为了演示目的。您不仅可以管道文件,还可以从其他命令输出

    ~$ echo "hello, world!" | ./search.sh
    here's the input i got:
    hello, world!
    

    如果要将输出重定向到另一个文件,请执行

    ~$ ./search.sh < foo.txt > bar.txt
    ~$ cat bar.txt
    here's the input i got:
    foo
    bar
    baz
    

    从 Ruby 读取文件

    另一种方法是将文件名作为参数传递并直接从 Ruby 中读取文件:

    #!/usr/bin/env ruby
    
    file = ARGV.first
    input = File.read(file)
    
    puts "here's the input i got:"
    puts input
    

    用法:

    ~$ ./search.sh foo.txt
    here's the input i got:
    asfdg
    sdf
    sda
    f
    sdfg
    fsd
    

    再次重定向输出使用&gt;

    ~$ ./search.sh foo.txt > bar.txt
    

    【讨论】:

      【解决方案2】:

      我假设输入文件的内容会有所不同,您将有一些逻辑来确定这一点。实际上,您可以只读取该文件输入,就好像它是用户以文本形式输入的一样,然后做任何您需要做的事情。

      例子:

      test.rb

      puts gets.chomp
      

      测试文件

      test
      

      终端

      $ ruby test.rb < testfile
      $ test
      

      【讨论】:

      • 这很有意义。我正在使用gets.chomp,但没有意识到如果你给它一个文件,它会立即完成gets.chomp。 (通常我在提示用户输入时使用gets.chomp。非常感谢这帮助了很多!
      • @p11y chomp 不是必需的,它取决于你想对输入做什么,我只是想表明它可以用作通常输入到程序中的文本。
      猜你喜欢
      • 1970-01-01
      • 2017-12-05
      • 2012-05-29
      • 2022-10-19
      • 1970-01-01
      • 2015-12-06
      • 1970-01-01
      • 2018-08-05
      • 2022-08-18
      相关资源
      最近更新 更多