We help IT Professionals succeed at work.

perl script to list size and modified name of files in folder

onyourmark
onyourmark asked
on
Hello. I have a folder with about 3600 files in it. The files have names like
11-05-26_08-00-01_sina.csv
11-05-26_12-00-01_sina.csv
11-05-26_16-00-01_sina.csv
11-05-26_20-00-01_sina.csv
11-05-27_00-00-02_sina.csv
11-05-27_04-00-01_sina.csv

I would like to get a csv file which consists of the modified names of the files and their file sizes (either mb or kb is ok). By modified name, I just want the year, month and day so that for example
11-05-26_08-00-01_sina.csv  
would become
11-05-26
and if this file was 25.2 mb the entry for this file would be
11-05-26, 25.2
Can anyone help me with this?
THANK YOU.
Comment
Watch Question

dda

Commented:
What is there are several files for single day, like in your example? 11-05-26 has 4 files.

Author

Commented:
Hi. Thanks for the reply!

Even if there are several files a day there can be a separate row for each one.

So it could look like

11-05-26, 25.2
11-05-26, 30.2
11-05-26, 20.8
11-05-26, 35.5

or something like that.

Thanks again.

How about something like this
use warnings;
use strict;

my @files = <*csv>;
foreach my $file (@files)
{
    my $size = (stat($file))[7];
    $file    =~ s/_.*//;
    print '"', join('","', ($file, $size )) , '"', "\n";
}

Open in new window

Author

Commented:
Hi. Thanks. To try this I should make it a file called something like sizes.pl and put it in the same directory as the files and then run it like
cd C:/appropriate directory
perl sizes.pl

Is this correct?

Thanks.
Yes.  Or if you want to run it from a different directory, you will have to change <*csv> part.
ozo
Most Valuable Expert 2014
Top Expert 2015

Commented:
print /([^_]*)/,", ",(-s)/1024,"\n" for <*.csv>;

Author

Commented:
how can I have the result written to a file called sizes.csv?
Thanks
You can redirect the output by using >

script.pl > sizes.csv

Author

Commented:
Hi. Thanks again.
I think I may have specified this incorrectly.

A file like 11-05-26_08-00-01_sina.csv
would be 2011/5/26

but it is reading it as  11/5/2026.

is this hard to rearrange?
Most Valuable Expert 2014
Top Expert 2015
Commented:
open STDOUT,">sizes.csv" or die $!;
printf "20%02d/%d/%d, %.3f\n",/(\d+)-(\d+)-(\d+)/,(-s)/1000 for <*.csv>;

Author

Commented:
THANKS!!!