ed3rick has asked for the wisdom of the Perl Monks concerning the following question:

i'm new to Perl and i want to rename various files on a directory with a string found on the file.

- The string that i want to use can be found on the 2nd line of each file which has a long date format (e.g. January 1, 2002, etc..).

- I want to be able to convert the string to YYYYMMDD and append it on the beginning of each file names that i want to rename.

example: abc001 will be renamed as 20020105-abc001

where abc001 is the old filename and 2002 as the year, 01 as the month and 05 as the day and append it on the beginning of the current file.

Thanks

Replies are listed 'Best First'.
Re: Converting Date to String
by choroba (Cardinal) on Jun 19, 2015 at 11:35 UTC
    Use Time::Piece to handle the date conversion. The following program works for files specified on the command line without path, so you have to cd to the containing directory before running it.
    #! /usr/bin/perl use warnings; use strict; use Time::Piece; for my $file (@ARGV) { open my $IN, '<', $file or do { warn "Can't open '$file', skipping.\n"; next }; <$IN>; # Skip the first +line. my $date_string = <$IN>; chomp $date_string; # Remove newline. my $date = 'Time::Piece'->strptime($date_string, '%B %d, %Y'); rename $file, $date->ymd(q()) . "-$file" or warn "Can't rename $fi +le\n"; }
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: Converting Date to String
by kcott (Archbishop) on Jun 19, 2015 at 12:12 UTC

    G'day ed3rick,

    Welcome to the Monastery.

    This annotated code should get you started:

    #!/usr/bin/env perl -l use strict; use warnings; # Set these constant values my %month_num_for = qw{ January 1 February 2 March 3 April 4 May 5 June 6 July 7 August 8 September 9 October 10 November 11 December 12 }; my $format = '%4d%02d%02d-%s'; # Get this data from file my $old_filename = 'abc001'; my $long_date = 'January 5, 2002'; # Split up the long format date my ($month, $day, $year) = split /\,?\s+/, $long_date; # Generate the new filename my $new_filename = sprintf $format, $year, $month_num_for{$month}, $day, $old_filen +ame; # For testing print "New filename: $new_filename"; # When you're happy with the testing # rename $old_filename => $new_filename

    Output:

    New filename: 20020105-abc001

    If you're unfamiliar with any of those functions, you'll find their documentation via "Perl functions A-Z".

    For any other parts of the code you don't understand, refer initially to "perlintro -- a brief introduction and overview of Perl". Each section in there has links to more detailed information: follow as required.

    -- Ken