It is not clear if the files should be renamed sequentially then moved to the new directory, or if the files should be moved then renamed.

Anyway, here is one way you might do the former... if you need the latter this can easily be adapted. This looks for all the .jpg files in the specified directory then only proceeds if there is a corresponding .xml file. The sort on @files is not strictly necessary and could be removed; glob() returns file names in OS sorting order. If you need some other order though, that is a good place to specify it.

Note: As this is written, if there are files already in one of the destination directories with the same name as the renamed jpeg/xml files, they will be clobbered.

use warnings; use strict; use File::Basename; use File::Copy; my $dir = 'ParticleAcquisitionDataImages/'; # or whatever my @files = glob "${dir}*.jpg"; my $rename_index = 1; for my $file ( sort @files ){ next if -d $file; my($filename, $directory, $suffix) = fileparse($file, '.jpg'); next unless -e "${dir}$filename.xml"; $filename = changename($filename); open my $fh, '<', "${dir}$filename.xml" or die "$!"; seek($fh, 498, 0); my $newdir; read($fh, $newdir, 3); close $fh; substr $newdir, 1, 1, ''; mkdir "$dir$newdir" unless -e "$dir$newdir"; for my $ext ( qw/.jpg .xml/) { move "$dir$filename$ext", "$dir$newdir/$filename$ext" or die $ +!; } } sub changename { my $filename = shift; for my $suffix ( qw/.jpg .xml/) { rename "$dir$filename$suffix", "$dir$rename_index$suffix" or d +ie $!; } return $rename_index++; }

In reply to Re: Renaming files in a directory in sequence by thundergnat
in thread Renaming files in a directory in sequence by Max79

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.