Topic: net/ftp get first file using wildcard

I'm trying to 'get' the first file that has a certain extention (msg) from a ftp location to my hard drive. So what I have is:

require 'net/ftp'
ftp ='ip.addrees')

So far everything is fine. I'm in the right folder. Using 'get' I can get the file to my harddrive but I don't actually want type the filename I want my little rubyscript to go to the first file meeting the *.msg criterium and then 'gets' it. I tried ftp.get('*.msg').first in all kinds of variations but that doesn't work. Anybody any ideas?


Re: net/ftp get first file using wildcard

the FTP GET command expects a real filename, no wildcards. you will have to get the directory list first. the list method returns an array with a string containing information for each file.

require "net/ftp"
ftp ="ip.addrees")


#get the file list, returns an array
files = ftp.list("*.msg")

# each element in the array is a string in the standard FTP list format:
# e.g.: "-rw-r--r-- ftpowner ftpowner 5748456 Nov 28 08:20:27 somefile.msg"
#so the filename we want is the last space-seperated element in this string

#split by space, returns an array
firstfile = files[0].split(" ")
# get the last element in this array, which is the filename
filename = firstfile[firstfile.size -1]
#get the file
ftp.get(filename) #gets file in current  mode (text or binary), or:
ftp.getbinaryfile(filename) #gets file in text mode, or:
ftp.gettextfile(filename) #gets file in binary mode

Last edited by Duplex (2007-11-29 10:44:01)

Re: net/ftp get first file using wildcard

Duplex thanks. It works like a charm except that I changed your

filename = firstfile[firstfile.size -1] to
filename =firstfile[-1]

Is that the same?


Re: net/ftp get first file using wildcard

oh sure, it is... D'Oh, should have thought of that smile

now you could shorten lines 14-16 into one line:

filename = files[0].split(" ")[-1]

Re: net/ftp get first file using wildcard

Im learning ruby, I need to know how to connect to a FTP server using a user and passwd, and then upload and download files from the server.
  I´d appreciate any help.