in reply to Parsing FTP ls command results

Though others have pointed out the FTP text is variable, one way to parse the provided text into directory and file listings is as follows:

#!/usr/bin/perl use warnings; use strict; while(<DATA>) { chomp; my @elements = split /\s+/, $_; if ( $elements[2] eq '<DIR>' ) { print "Directory: ",$elements[3], "\n"; } else { print "The size of $elements[3] is $elements[2] bytes.\n"; } } __DATA__ 03-26-07 05:23AM <DIR> html 03-26-07 04:27AM <DIR> ibm-laptop 03-26-07 03:16AM <DIR> images 03-27-07 11:00PM 6397 index.html 03-26-07 03:45AM 10186 index1.html
And if this code is run:

~/perl/monks$ ./parselist.pl Directory: html Directory: ibm-laptop Directory: images The size of index.html is 6397 bytes. The size of index1.html is 10186 bytes.

Replies are listed 'Best First'.
Re^2: Parsing FTP ls command results
by johngg (Canon) on Sep 13, 2007 at 12:44 UTC
    I'm not sure how file names with spaces will be displayed by the FTP command but I would probably use the three argument form of split just to be safe. I would also use a list on the LHS rather than an array for readability.

    my ($date, $time, $typeOrSize, $name) = split /\s+/, $_, 4;

    Cheers,

    JohnGG

      thanks to you john... your comment help me so much, thanks again!
Re^2: Parsing FTP ls command results
by roboticus (Chancellor) on Dec 09, 2010 at 13:32 UTC

    dwm042:

    Yes, but some FTP servers will give you some even uglier output, like:

    125 List started OK. Volume Unit Date Ext Used Recfm Lrecl BlkSz Dsorg Dsname APCSPL 3380D 07/16/97 1 1 FB 80 8800 PS ETC.RPC APCSPL 3380D 08/03/97 1 1 FB 80 3200 PS ETC.SERVICES APCSPL 3380D 08/03/97 1 1 FB 80 3120 PS FTP.DATA APCSPL 3380D 08/02/97 1 1 F 158 158 PS HOSTS.ADDRINFO APCSPL 3380D 08/03/97 1 1 FB 80 3120 PS HOSTS.LOCAL APCSPL 3380D 07/30/97 1 1 F 56 56 PS HOSTS.SITEINFO 250 List completed successfully.

    So if you're trying to be tolerant of multiple FTP servers, be aware that you may have to have multiple parsers. (Note: The above was snipped from the IBM help pages.)

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.