如何在 Ruby 中将文本文件作为参数传递

问题描述 投票:0回答:2

我需要将文本文件作为参数传递,而不是在代码中打开它。文本文件的内容应该打印在控制台上。我做了以下代码:

File.open("test_list.txt").each do |line|
    puts line
end

请指教

ruby file text
2个回答
5
投票

在您的 shell 上,调用

ruby
脚本,然后调用
.txt
文件的名称,如下所示:

ruby foo.rb test_list.txt

变量

ARGV
将包含对调用
ruby
解释器时传递的所有参数的引用。特别是
ARGV[0] = "test_list.txt"
,因此您可以使用它而不是对文件名进行硬编码:

File.open(ARGV[0]).each do |line|
    puts line
end



另一方面,如果你想将文件的content传递给你的程序,你可以使用:

cat test_list.txt | ruby foo.rb

在节目中:

STDIN.each_line do |line|
    puts line
end

1
投票

Ruby 有 Perl / awk / sed 根。与 Perl 和 awk 一样,您可以使用读取 stdin 或打开文件名的“魔法”(如果在命令行上提供了相同的代码)。

给定:

$ cat file
line 1
line 2
line 3

您可以编写一个类似

cat
的实用程序来打开一个命名文件:

$ ruby -lne 'puts $_' file
line 1
line 2
line 3

或者,同样的代码,将逐行读取标准输入:

$ cat file | ruby -lne 'puts $_'
line 1
line 2
line 3

在这种特殊情况下,它来自

-lne
命令行参数到 Ruby。

 -n             Causes Ruby to assume the following loop around your
                script, which makes it iterate over file name arguments
                somewhat like sed -n or awk.

                      while gets
                        ...
                      end

 -l             (The lowercase letter ``ell''.)  Enables automatic line-
                ending processing, which means to firstly set $\ to the
                value of $/, and secondly chops every line read using
                chop!.

 -e command     Specifies script from command-line while telling Ruby not
                to search the rest of the arguments for a script file
                name.

不使用

-n
开关,您还可以使用 ARGF 流并修改您的代码,以便它以相同的方式使用
stdin
或命名文件。

命名文件:

$ ruby -e '$<.each_line do |line|
    puts line
end' file
line 1
line 2
line 3

使用相同的代码阅读

stdin

$ cat file | ruby -e '$<.each_line do |line|
    puts line
end' 
line 1
line 2
line 3

或者打开名为命令行参数的文件:

ruby -e 'ARGV.each{|arg| 
    puts "\"#{File.expand_path(arg)}\" contains:"
    puts File.open(arg).read
}
' file 
"/tmp/file" contains:
line 1
line 2
line 3
© www.soinside.com 2019 - 2024. All rights reserved.