#! /usr/local/bin/perl # #Script searches and copies large quantities of files # #Script reads a list of IDs given in a text file, #searches for filenames in a specified directory, # and copies all the files, which have the ID as a part of their name # into a new directory given that file exists in source dir #and does not exist in target dir! # #Results are reported into text file. # #Script doesn't work, if text file is created by parsing #a csv file and writing the IDs into the text file #Solution: Remove carriage return: $/="\r\n"; then: chomp # #tested: --ok! ############################################################### #use strict; use warnings; use File::Copy; #Input Source directory --ok! my $dir = $ARGV[0]; if ( !$ARGV[0] ) { print "Error: Missing input directory!\n"; } if ( !-d $ARGV[0] ) { print "Error: Input is no directory\n"; } #Open filehandle and parse list from a text file --ok! my $ref = "./data/indexIDs.txt"; #Important: Text file must not contain carriage returns!!! open(FH, '<', $ref) or die "Cannot open file: \n$!"; my @ids = ; chomp @ids; #print "$_\n" for @ids; # tested --ok! close (FH); #test target directory --ok! my $dirTarget = "/cygdrive/d/bildimport/"; if( !-d $dirTarget) { print "Can not open $dirTarget: $!\n"; } #Scan a directory and write filenames into an array --ok! opendir (SOURCE, $dir)or die "Cannot open dir: $!\n"; foreach my $file (readdir SOURCE) { push (@dirFile, $file); chomp @dirFile; } closedir SOURCE; #Report results of copying process into a text file # 3 possible options: #file copied; #file not copied: file exists; #file not copied: file not found open OUT, '>./data/results.txt' or die "Cannot open file: $!\n"; ######################################################################### ###MAIN #Use element of @ds as regex and search for all matches in @dirFile --ok! #Copy file, if filename matches foreach my $line (@ids) { if (grep /$line/, @dirFile) { my @result = grep (/$line/, @dirFile); foreach (@result) { #print OUT "$_\n"; #tested: --ok! #Build path to files in source dir and to target directory my $res = $dir.$_, "\n"; my $tar = $dirTarget.$_, "\n"; #Start copy! if (!-e $tar) { copy ($res, $tar) or die "Cannot copy: $!"; print OUT "$_ ;;;copied!\n"; } else { print OUT "$_ ;;;not copied: file exists!\n"; } } } else { print OUT "$line ;;;not copied: file not found!\n"; } } close OUT;