如何在命令行中使用<读取ruby中的输入文件?

JP.*_*JP. 1 ruby terminal command input output

我想要这个工作:

./search.sh < inputFile.json
Run Code Online (Sandbox Code Playgroud)

./search.sh < inputFile2.json
Run Code Online (Sandbox Code Playgroud)

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

(./search.sh < inputFile.json) > results.json
Run Code Online (Sandbox Code Playgroud)

我确定语法错误。有谁能够将我带往正确的方向?我在我的ruby脚本中找不到如何执行此操作(我使用的是.sh但它是ruby)。

Pat*_*ity 5

您有多种选择。

从stdin读取

一种选择是从stdin读取。您可以例如在search.sh

#!/usr/bin/env ruby

input = $stdin.read

puts "here's the input i got:"
puts input
Run Code Online (Sandbox Code Playgroud)

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

foo
bar
baz
Run Code Online (Sandbox Code Playgroud)

然后您可以将其与unix管道一起使用

~$ ./search.sh < foo.txt
here's the input i got:
foo
bar
baz
Run Code Online (Sandbox Code Playgroud)

相当于

~$ cat foo.txt | ./search.sh
here's the input i got:
foo
bar
baz
Run Code Online (Sandbox Code Playgroud)

尽管这是对猫的无用使用,仅用于演示目的。您不仅可以管道文件,还可以从其他命令输出

~$ echo "hello, world!" | ./search.sh
here's the input i got:
hello, world!
Run Code Online (Sandbox Code Playgroud)

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

~$ ./search.sh < foo.txt > bar.txt
~$ cat bar.txt
here's the input i got:
foo
bar
baz
Run Code Online (Sandbox Code Playgroud)

从Ruby读取文件

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

#!/usr/bin/env ruby

file = ARGV.first
input = File.read(file)

puts "here's the input i got:"
puts input
Run Code Online (Sandbox Code Playgroud)

用法:

~$ ./search.sh foo.txt
here's the input i got:
asfdg
sdf
sda
f
sdfg
fsd
Run Code Online (Sandbox Code Playgroud)

并再次重定向输出使用 >

~$ ./search.sh foo.txt > bar.txt
Run Code Online (Sandbox Code Playgroud)