n00b question alert!
here is the problem:
I am creating a shell script that takes a minimum of 3 arguments: a string, a line number, and at least one file.
I’ve written a script that will accept EXACTLY 3 arguments, but I don’t know how to handle multiple file name arguments.
here’s the relevant parts of my code (skipping the writing back into the file etc):
#!/usr/bin/env ruby
the_string = ARGV[0]
line_number = ARGV[1]
the_file = ARGV[2]
def insert_script(str, line_n, file)
f = file
s = str
ln = line_n.to_i
if (File.file? f)
read_in(f,ln,s)
else
puts "false"
end
end
def read_in(f,ln,s)
lines = File.readlines(f)
lines[ln] = s + "\n"
return lines
end
# run it
puts insert_script(the_string, line_number, the_file)
now I know that it’s easy to write a block that will iterate through ALL the arguments:
ARGV.each do |a|
puts a
end
but I need to ONLY loop through the args from ARGV[2] (the first file name) to the last file name.
I know there’s got to be – at a minimum – at least one easy way to do this, but I just can’t see what it is at the moment!
in any case – I’d be more than happy if someone can just point me to a tutorial or an example, I’m sure there are plenty out there – but I can’t seem to find them.
thanks
If you modify the
ARGVarray to remove the elements you’re no longer interested in treating as filenames, you can treat all remaining elements as filenames and iterate over their contents withARGF.That’s a mouthful, a small example will demonstrate it more easily:
argf.rb:There are two copies of the
argf.rbfile printed to the console because I gave the filenameargf.rbtwice on the command line. It was opened and iterated over once for each mention.If you want to operate on the files as files, rather than read their contents, you can simply modify the
ARGVarray and then use the remaining elements directly.