Praveenks
Praveenks

Reputation: 1496

Pattern matching not working while copying files

I want to copy some specific files form a folder to another folder. The source folder is having these kind of files:

Example:

abc_key_in.rsb
abc_key_in_at.rsb
abc_key_in.kwd
abc_key_in_at.kwd...

I have to copy files which are having abc_key_ as prefix and .kwd as an extension....

I have tried this code but pattern matching is not working...

foreach $filename(@files)
{   

   if($file_name =~/abc_key_*.kwd/) <--- Not working
   {
        print $file_name;
        cp($file_name,$dest_dir.$file_name) #or die "Failed to copy $file_name :$!\n";
    }
 }

Upvotes: 1

Views: 145

Answers (4)

Miller
Miller

Reputation: 35208

Your use of * is reminiscent of shell wildcards and not regular expressions.

To do that, you want glob:

use strict;
use warnings;

use File::Copy;

my $src_dir  = '/foo/bar';
my $dest_dir = '/biz/baz';

for my $file ( glob("$src_dir/abc_key_*.kwd") ) {
    copy( $file, $dest_dir ) or die "Can't copy $file to $dest_dir: $!";
}

Alternatively, I would recommend using Path::Class for cross platform compatible file and directory processing:

use strict;
use warnings;

use Path::Class;

my $src_dir  = dir('/foo/bar');
my $dest_dir = dir('/biz/baz');

for my $file ( $src_dir->children ) {
    next if $file->is_dir || $file !~ /abc_key_.*\.kwd$/;
    $file->copy_to($dest_dir) or die "Can't copy $file: $!";
}

Upvotes: 1

vks
vks

Reputation: 67988

^abc_key_[^.]*\.kwd$

Try this This will match only files requiring your needs.See demo.

http://regex101.com/r/aX5eP7/2

Upvotes: 0

Lee Duhem
Lee Duhem

Reputation: 15121

You can use File::Find to find out files and File::Copy to copy them, like this:

#!/usr/bin/perl

use strict;
use warnings;

use File::Find;
use File::Copy;
use File::Path qw(make_path);
use File::Spec::Functions qw(rel2abs);

my $src = rel2abs('src');
my $dest = rel2abs('dest');

# create destination directory
make_path("$dest");

# find and copy files
find(\&wanted, $src);

sub wanted {
    if (m/^abc_key_.*\.kwb$/) {
        copy($File::Find::name, $dest) or die "Copy failed: $!";
    }
}

Upvotes: 1

Robby Cornelissen
Robby Cornelissen

Reputation: 97282

You might want to read up on regular expressions and pattern matching, because you're not using the correct syntax. Try like this:

if ($file_name =~ /^abc_key_.*\.kwd$/) {
    # ...
}

Meta-characters used in the regular expression:

  • ^ denotes the start of the string
  • . is the wildcard character
  • * is a quantifier (0 or more)
  • \. is the literal dot character
    (need to escape the dot because otherwise it would be interpreted as the wildcard character)
  • $ denotes the end of the string

Upvotes: 1

Related Questions