Brettski
Brettski

Reputation: 1051

Ruby Net::FTP, extract filename from ftp.list()

I'm using the following code to try and get all files from ftp using Ruby.

files = ftp.list()

files.each do |file|
  ftp.gettextfile(file)
end

The problem is ftp.list returns a whole line of information, not just the filename e.g.

-rw-r--r-- 1 ftp ftp              0 May 31 11:18 brett.txt

How do I extract the filname from this string?

Many thanks

Upvotes: 10

Views: 7993

Answers (3)

Jamie Buchanan
Jamie Buchanan

Reputation: 3938

You can use the nlst public method like this

files = ftp.nlst("*.zip")|ftp.nlst("*.txt")|ftp.nlst("*.xml")

#optionally exclude falsely matched files
exclude = /\.old|temp/ 

#exclude files with 'old' or 'temp' in the name
files = files.reject{ |e| exclude.match e } #remove files matching the exclude regex

files.each do |file|
  #do something with each file here
end

Upvotes: 22

Indika K
Indika K

Reputation: 1414

If you want to process the output of ftp.list you may find net-ftp-list useful.

Upvotes: 0

rubysolo
rubysolo

Reputation: 543

However, list appears to be useful, as you can pass in a matching pattern, which it doesn't appear that nlst supports. I just did a quick-and-dirty hack to make list output work:

ftp.list("*.zip") do |zipfile|
  zipfile = zipfile.split(/\s+/).last
  # ... do something with the file
end

Upvotes: -2

Related Questions