Solved

Perl - Find File by pattern, set it to a variable

Posted on 2014-07-25
2
287 Views
Last Modified: 2014-07-25
First off, I am absolutely new to Perl. This is a situation of 'learn on the fly' due to someone leaving and Perl scripts were dumped into my lap.

Initially, the code was taking a specific file name and doing a process. Now I need to scan a directory for a pattern, if the pattern is found, get the file name and set it to a variable for a function to then process. The initial thought when this person wrote this was there would only be one file called U0001, and it's being passed to the script as positional parameter 1, with full path. Parm 2 is the location to move the file to.  I know he did this so he could use it for any file and any output.

Now there can be upwards of hundreds of Uxxxx files. I need to process then one by one.  The program does look at the file contents, and based on contents, does a rename.

This works if I pass it a very specific name. I just don't know where to begin to have it look at a directory (let's just call it /user/input) for the pattern, capture the file name, and set it to a variable that the rest of program can use.

Thanks in advance.

#!/usr/bin/perl
use File::Copy;

open(FILE,"$ARGV[0]") or die "No Files found to Process: $!";
        while(<FILE>) {
                push(@LIST,"$_");
        }
close(FILE);


foreach $LINE (@LIST) {

        if ($LINE =~ /ORANGES/) {

                print "ORANGES file found--now renaming\n\n";

                rename("$ARGV[0]","${ARGV[0]}_ORANGES") or die "Can't rename file with ending _ORANGES: $!";
                                move ("${ARGV[0]}_ORANGES","${ARGV[1]}/.");
                exit;
        } elsif ($LINE =~ /APPLES/) {

                print "APPLES file found--now renaming\n\n";

                rename("$ARGV[0]","${ARGV[0]}_APPLES") or die "Can't rename file with ending _APPLES: $!";
                move ("${ARGV[0]}_APPLES","${ARGV[1]}/.");
                                exit;
        }

}
print "No Pattern found in file--exit 99\n\n:";
exit 99;

Open in new window

0
Comment
Question by:PAH_in_MI
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 26

Accepted Solution

by:
wilcoxon earned 500 total points
ID: 40220061
Something like this should work.  I added use strict and warnings (which you should *always* do) which necessitated other modifications.  I also made some changes for efficiency.  I don't think whoever wrote this really understood Perl well.
#!/usr/bin/perl
use strict;
use warnings;
use File::Copy qw(mv);

my $dir = shift or die "Usage: $0 src_dir dest_dir\n";
my $dest = shift or die "Usage: $0 src_dir dest_dir\n";

# get a list of all files matching Uxxx where xxx is numbers in the dir
opendir DIR, $dir or die "could not open dir $dir: $!";
my @files = grep /^U\d+$/, readdir DIR;
closedir DIR;

foreach my $fil (@files) {
        process("$dir/$fil");
}

sub process {
my ($fil) = @_;

open FILE, $fil or die "could not open $fil: $!";
my $new;
while (<FILE>) {
        # more compact/efficient method
        if (/(ORANGES|APPLES)/) {
                print "$1 file found--now renaming\n\n";
                $new = $fil . '_' . $1;
                last;
        }
# "old" method
#        if (/ORANGES/) {
#                print "ORANGES file found--now renaming\n\n";
#                $new = $fil . '_ORANGES';
#                last;
#        } elsif (/APPLES/) {
#                print "APPLES file found--now renaming\n\n";
#                $new = $fil .= '_APPLES';
#                last;
#        }
}

if ($new) {
        $new =~ s{^$dir}{$dest};
        mv $fil, $new or die "could not move $fil to $new: $!";
} else {
        print "No Pattern found in file--exit 99\n\n:";
        exit 99;
}

Open in new window

0
 

Author Closing Comment

by:PAH_in_MI
ID: 40220191
You rock wilcoxon!!

And I can actually read the code and understand it. Thanks!
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Any syntax error for this clone.plscript 6 150
Perl string filter 5 88
Vb script to unzip a files and rename the files 12 134
Perl tar error 8 75
Email validation in proper way is  very important validation required in any web pages. This code is self explainable except that Regular Expression which I used for pattern matching. I originally published as a thread on my website : http://www…
There are many situations when we need to display the data in sorted order. For example: Student details by name or by rank or by total marks etc. If you are working on data driven based projects then you will use sorting techniques very frequently.…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…

752 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question