使用通配符在多个输入文件上调用 Ruby 脚本
我对 Ruby 比较陌生,需要编写一个处理多个输入文件的脚本。应该这样调用:
script.rb -i file*
其中目录包含多个文件,例如 file1.xml
、file2.xml
等。 只是一个简单的问题:这个通配符将如何扩展?我需要在我的脚本中对其进行编程吗?我正在使用 OptionParser 类来解析命令行参数。
谢谢!
I am relatively new to Ruby and need to write a script that will handle mulitple input files. It should be called like so:
script.rb -i file*
where the directory contains multiple files, like file1.xml
, file2.xml
and so on.
Just a quick question: How will this wildcard be expanded? Do I need to program that in my script? I am using the OptionParser
Class for parsing commandline arguments.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
通配符由命令行扩展,因此您将获得目录中每个文件的列表。
如果这样做,
Ruby 会将字符串 *.txt 转换为匹配的文件名并传入
扩展数组作为新参数。
使用 optparse:
将打印出:
将导致 options[:files] 成为字符串数组
http:// /www.ruby-forum.com/topic/111252
The wildcard is expanded by the command line so you'll get a list of each file in the directory
If you do,
Ruby converts string *.txt into the matching filenames and pass in the
expanded array as the new argument.
Using optparse:
Will print out:
Will result in options[:files] being an array of strings
http://www.ruby-forum.com/topic/111252
使用
-i
开关和文件列表是一个奇怪的想法,如果您的脚本接受文件,可能不需要-i
并使用开关作为其他选项?如果是这样,只需使用ARGV
。Strange idea to use
-i
switch and than list of files, if your script accepts files maybe do it without-i
and use switches for other options? If so just useARGV
.对于 Unix,如果您想将通配符传递给 Ruby 本身,那么您需要对其进行转义(例如,将其放在引号内)。当命令行对所涉及的文件数量感到困惑时,我使用了这种方法(这可能是一个坏兆头!)。
For Unix, if you want to pass the wildcard to Ruby itself, then you need to escape it (eg by putting it within quotation marks). I used this approach when the command line was barfing at the number of files involved (which is probably a bad sign!).