Rename files based on arithmetic rules gained from another directory in perl on windows

StackOverflow https://stackoverflow.com/questions/18709050

  •  28-06-2022
  •  | 
  •  

Question

So I need to loop through some files in an array, and increase the number contained in the line by the number of ")_Graph_S1.dat" files in the directory below. I next need to rename the file to with the replaced number so that plate0013 (44)_Graph_S1.dat would become plate0013 (88)_Graph_S1.dat if there were 44 files in the below directory. For example, I'm working in the directory: plate0013\2nd run\. I need to rename the files in the directory \2nd run\ based on the number of ")_Graph_S1.dat" files in the plate0013 directory.

I'm using windows 7 and strawberry perl.

I have tried the code located here: https://stackoverflow.com/a/5029064/2060081, but my output is not changed.

I haven't figured out how to get a count of the files in the previous directory, so I have used the filler 44 until I'm no longer stuck. Here are the important parts of my code:

my @array = glob('*)_Graph_S1.dat');

foreach (@array) {
    my $in = $_;
    $in =~ s/(\d+)\)/$1+44/e;
    rename $_, %in;
}

My problem is that I need to include the parenthetical in the new name, and I cannot figure out how to do this.

I've never used regular expressions before, and I haven't programmed in perl since 1995. My google skills have failed me. Thank you for reading and for your replies.

So thanks to @TLP, I've figured out why my system code wasn't outputting properly. But I've discovered a problem with my Regular Expression. My files are named like plate 0013 (01)_Graph_S1.dat. But it does not include the parenthetical in the new name.

Was it helpful?

Solution

Assuming that @array contains files from 2nd run,

use strict;
use warnings;

my @array = glob('*)_Graph_S1.dat');

# forcing list context => perldoc -f glob
my $number_of_files_in_dir_below = @{[ glob('../*)_Graph_S1.dat') ]};

foreach (@array) {
    my $in = $_;
    $in =~ s/(\d+)\)/$1+$number_of_files_in_dir_below .")"/e;
    rename $_, $in;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top