您有多种选择。
从标准输入读取
一种选择是从标准输入读取。例如,您可以在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
再次重定向输出使用>
~$ ./search.sh foo.txt > bar.txt