Categories
Q & A Q & A Code

⨘ } recursive folder structure based on excel spreadsheet information – perl

Below a simple perl script to make directory folder structure which may be helpful for you if you need to deal with thousands of folders.
Example: folder_structure.csv (you may extract csv fromat from excel sheet). We need to make folder structure as continent folder contains regions, regions contains countries, each country contains states etc.
ASIA,SOUTH ASIA,INDIA
ASIA,SOUTH ASIA,PAKISTA
NORTH AMERICA,CANADA,ONTARIO
NORTH AMERICA,USA,MASSACHUTTES

script: folders.pl

#!/usr/bin/perl

use strict;
use warnings;

use Cwd;

print “\n”;
print “FILE USED = $ARGV[0]”;
print “\n”;

my $work_dir=getcwd();
print “CURRENT DIR = $work_dir”;
print “\n”;

open (F_CONT, ‘<‘, $ARGV[0]) or die “\n no file to open”;

my $root_folder = (“COUNTRY FOLDERS”);
doFold($root_folder);
chdir $root_folder;

while(){
chomp $_;
my @words = split /,/, $_;

foreach (@words) {
if (-e $_) { print “$_ exists\n”; }
else { mkdir $_ or die “Error creating directory: $_\n”; print “Created folder: $_\n”; }
chdir $_;
}

#doFold(@mycountryfolders);

chdir $work_dir;
chdir $root_folder;
}

chdir $work_dir;

##
sub doFold {
foreach (@_) {
if (-e $_) { print “$_ exists\n”; }
else { mkdir $_ or die “Error creating directory: $_\n”; }
}
}
##

I have commented doFold subroutine, but you can modify script above to use subroutines as well. This script is written for Linux/MAC machines.

For windows: you may need to install perl which you may install from an authenticate source, e.g. perl.org

 1,637 total views,  2 views today

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.