Solved

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

Posted on 2014-07-25
2
267 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
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

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Suggested Solutions

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…
In the distant past (last year) I hacked together a little toy that would allow a couple of Manager types to query, preview, and extract data from a number of MongoDB instances, to their tool of choice: Excel (http://dilbert.com/strips/comic/2007-08…
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…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

707 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now