Bullu
Bullu

Reputation: 23

Need a Perl script to match a string in all files inside a directory and push matching ones to new folder

I want a Perl script to search in the mentioned directory and find those files which contains the string ADMITTING DX and push those files to a new folder.

I am new to Perl and was trying this:

#!/usr/bin/perl

use strict;
use warnings;

use File::Find;

my $dir    = '/usr/share/uci_cmc/uci_new_files/';
my $string = 'ADMITTING DX';

open my $results, '>', '/home/debarshi/Desktop/results.txt'
    or die "Unable to open results file: $!";

find(\&printFile, $dir);

sub printFile {

    return unless -f and /\.txt$/;

    open my $fh, '<',, $_ or do {
        warn qq(Unable to open "$File::Find::name" for reading: $!);
        return;
    };

    while ($fh) {
        if (/\Q$string/) {
            print $results "$File::Find::name\n";
            return;
        }
    }
}

Upvotes: 1

Views: 1645

Answers (4)

Borodin
Borodin

Reputation: 126772

There are two errors in your code. Firstly you have a superfluous comma in the open call in printFile. It should read

open my $fh, '<', $_ or do { ... };

and secondly you need a call to readline to fetch data from the opened file. You can do this with <$fh>, so the while loop should read

while (<$fh>) { ... }

Apart from that your code is fine

Upvotes: 0

s0me0ne
s0me0ne

Reputation: 516

And if you still need a Perl solution:

perl -e 'for my $f (glob "*.txt") { open F, $f or die $!; while(<F>){ if(/ADMITTING DX/){ rename $f, "/path/to/destination/$f" or die $!; last } close $f; }}'

Upvotes: 0

s0me0ne
s0me0ne

Reputation: 516

You can really do it with Perl and that's a great way. But there's no any complex text processing in your case so I'd just advise using bash one-liner:

for f in *.txt; do grep 'ADMITTING DX' $f >/dev/null && mv $f /path/to/destination/; done

Upvotes: 1

codaddict
codaddict

Reputation: 455440

You are reading the lines from the file as:

while ($fh)

which should be

while (<$fh>)

Upvotes: 2

Related Questions