user2361820
user2361820

Reputation: 449

Need to download most recent .txt file from a ftp directory and save it

Basically I need to download a txt file that updates and changes names each day and open it in Excel. My problem is that I'm doing this for a MAC and I can't find the necessary modules for VBA (as far as I can tell)

So I've resorted to writing a PERL script to actually download the file, and then I'll just make a VBA script to open the newest file. I've successfully used the net:ftp module to actually download the file, what would be the best way to search by date and only download the newest file? Additionally, would fetch be the better option? the ftp site doesn't require credentials.

#!/usr/bin/perl
use Net::FTP;
use strict;
use warnings;

my $ftp = Net::FTP->new("ftp.site", Debug => 0)
 or die;

$ftp->login("anonymous",'-anonymous')
 or die, $ftp->message;

$ftp->cwd("/public/doc/cor/")
 or die;

$ftp->get("20130614c.txt")
 or die , $ftp->message;

$ftp->quit;

Upvotes: 0

Views: 684

Answers (2)

James
James

Reputation: 4737

If you can always check for the name according to the current day then just create a formatted string of today's date:

my($sec, $min, $hour, $mday, $mon, $year) = localtime(time);
$year += 1900;
$mon += 1;

my $today = sprintf("%04d%02d%02d", $year, $mon, $mday);

Now you have the file name according to your conventions:

$ftp->get("${today}c.txt")

If you need a date other than current date, then you can use a date math library to calculate the date you need and format it accordingly. I personally always use Date::Calc.

And of course, make sure to handle the error gracefully if the file doesn't exist on the ftp host yet.

Upvotes: 1

Massa
Massa

Reputation: 8972

As your file names are date-based, you can just do:

$ftp->get( [sort($ftp->ls)]->[-1] )

since that would be your newest file...

Upvotes: 2

Related Questions