XXDebugger
XXDebugger

Reputation: 1581

Extract specific data from multiple text files in a directory

This is my first program in perl. I have more than 1000 files and I want to extract specific data from a file. The structure of all the files are same. Its really difficult to open every file and then copy a specific data,

How can I achieve this using perl.

The structure looks like this.

    LensMode=Normal
    MicronMarker=500
    DataDisplayCombine=1
    Voltage=0 Volt
    PixelSize=1.586612

I want to extract MicronMarker and PixelSize from each file. Any help in the right direction is appreciated.

the location is D:\Files\Folder1

Upvotes: 0

Views: 489

Answers (1)

mkHun
mkHun

Reputation: 5927

Try this

Use glob to read the directory

while (my $files = glob(" D:\Files\Folder1\*"))
{
    open my $handler,"<","$files";
    my @extract = grep{ m/^(MicronMarker|PixelSize)/g} <$handler>;  
    print @extract;
}

Extract the word from a file using the while loop by opendir.

opendir(my $dir, " D:\Files\Folder1");

while (my $ech = readdir($dir))
{
    open my $handler,"<","test/$ech";
    while(my $l = <$handler>)
    {
        if($l =~m/^(?:MicronMarker|PixelSize)/g)
        {
            print "$l";

        }

    }
    close ($handler);
}

This is easy way to extract a words from a file using grep

while (my $ech = readdir($dir))
{
    open my $handler,"<","test/$ech";
    my @extract = grep{ m/^(MicronMarker|PixelSize)/g} <$handler>;
    print @extract;
    close($handler);
}

Upvotes: 2

Related Questions