Search code examples
perlperl-data-structures

Grep data from multiple file then feed into a log


I want to grep data from multiple files then combine the data I grep into a single log. My input files as such:

Input file1 (200MHz)

Cell_a  freq_100  50
Cell_a  freq_200  6.8
Cell_b  freq_100  70

Input file2 (100MHz)

Cell_a  freq_100  100
Cell_a  freq_200  10.5
Cell_b  freq_100  60

This is my expected output

<cell>  <freq> <value_frm__file2> <value_frm_file1> <etc>

Example expected output:-

Cell_a  freq_100 100 50
Cell_a  freq_200 10.5 6.8
Cell_b  freq_100 60 70 

I only able to grep the value once in a time. Can someone help in solving this? Thanks a bunch!


Solution

  • Try this:

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    use feature qw(switch say);
    
    my %record;
    
    while (<>) {
        chomp;
        my ($cell, $freq, $num) = split " ";
    
        push @{$record{$cell}->{$freq}}, $num;
    }
    
    while (my ($cell, $freqs) = each %record) {
        while (my ($freq, $nums) = each %$freqs) {
            say "$cell $freq ", join(" ", @$nums);
        }
    }
    

    Run it like this:

    ./t.pl input1.txt input2.txt