views:

43

answers:

4

Hi,

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!

+3  A: 

The wildcard is expanded by the command line so you'll get a list of each file in the directory

C:\working>dir *.txt

05/10/2007 03:24 PM 46,101      config.txt
11/23/2004 11:54 AM 361           tips.txt
2 File(s) 46,462 bytes

If you do,

C:\working>ruby -e "puts ARGV" *.txt
config.txt
tips.txt

Ruby converts string *.txt into the matching filenames and pass in the expanded array as the new argument.

Using optparse:

options = {}
OptionParser.new do |opts|
    opts.on("-i", Array, "List files") do |v|
      options[:files] = v
    end
  end.parse!

p options

C:\working> script.rb -i *.txt

Will print out:

["config.txt","tips.txt"]

Will result in options[:files] being an array of strings

http://www.ruby-forum.com/topic/111252

AdamH
Thanks.. and how would I parse the argument array (is it an array?) with the `OptionParser`?
slhck
I edited my post to show how it works with OptionParser
AdamH
Thank you very much. Much appreciated.
slhck
+2  A: 

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 use ARGV.

tig
Yeah, thanks, that's what I did in another script, worked fine too!
slhck
A: 
Dir["*.txt"].each do |file|
   o = open("tempfile","a")
   open(file).each do |line|
     # lines for processing
     # .....
       o.write(...)
   end
   o.close
   File.rename("tempfile",file)
end 
ghostdog74
A: 

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!).

Andrew Grimm