[英]Multiple files as command line arguments?
我編寫了一個腳本來從文件中讀取IP地址並在文件中打印金額。 我並不完全滿意,因此我嘗試對其進行修改以允許讀取多個文件,並且我將通過cmd參數指定文件。 我遇到的問題是它似乎讀取多個文件作為一個參數。
def host_count(*files)
begin
files.each do
files = files.join(' ')
read = IO.read(files)
reg = read.scan(/(?:\d{1,3}\.){3}\d{1,3}/).size
puts "There are " << reg.to_s << " IP addresses in #{files}."
end
rescue Errno::ENOENT
puts "File #{files} does not exist!"
rescue TypeError
puts "Usage: #{$0} [file]"
puts "Example: #{$0} /home/user/ipfile.txt"
end
end
host_count(ARGV)
使用多個文件運行此腳本會出現以下錯誤:
文件file1 file2不存在!
它們之間沒有逗號或其他任何分隔符,因此它沒有將我的參數讀為:[“ file1”,“ file2”],這是我最初的問題。 我不明白什么?
你寫了
files.each do
files = files.join(' ')
為什么要這么做? 您正在更改數組。.“ files”數組已經是一個數組,您不必將其與字符串連接。
edit1:要獲取每次運行的特定文件,您應該編寫:
files.each do |file|
puts file # will print "file 1", and in the next iteration will print "file 2".
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.