vkk05
vkk05

Reputation: 3222

Perl match file content using grep or read line by line

I have a file with below content. Based on perticular condition I want to extract column1 data.

Input file:

RT0AC1 127.0.0.1
RT1AB1 127.0.0.1
RT2AC1 127.0.0.1
RT3AC3 127.0.0.1
ST1AC1 127.0.0.1
WA1RA1 127.0.0.1
WB1RQ1 127.0.0.1
WG3RA3 127.0.0.1

Data which is needed:

RT0AC1
RT2AC1
RT3AC3
ST1AC1
WA1RA1
WG3RA3

Here I have written a Perl script which can able to store the data in $data. But not able to write the data in out_file.txt.

#!/usr/bin/perl

use strict;
use warnings;

my $data = system('grep "AC\|RA" file.txt  | awk -F" " \'{if((substr($1,4,2) == "AC")||(substr($1,4,2) == "RA")){print $1}}\'');

print $data;

my $file = "out_file.txt";
open my $fh, ">:encoding(utf8)", $file or die "$file: $!";

print $fh $data;
close $fh;

#script continues..

The content of out_file.txt is blank. Am I doing anything wrong?

Do you suggest me to read the file.txt content line by line and match the content using regex and write the content to out_file.txt instead of searching using grep.

Which one would be faster?

Edit:

This is not my end of the script. I need to do further process in my script. So if you suggest perl one liner or awk I need to execute the way @toolic as suggested.

Upvotes: 2

Views: 553

Answers (1)

glenn jackman
glenn jackman

Reputation: 246764

It's nonsensical to call out to grep and awk from perl:

#!/usr/bin/env perl
use strict;
use warnings;
use autodie;

my @data;
open my $fin,  "<:encoding(utf8)", "file.txt";
while (<$fin>) {
    my $word = (split)[0];
    my $code = substr($word, 3, 2);
    push @data, $word if grep {$_ eq $code} qw(AC RA);
}
close $fin;

open my $fout, ">:encoding(utf8)", "out_file.txt";
print $fout join("\n", @data), "\n";
close $fout;

Upvotes: 3

Related Questions