Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

running awk command in perl

Tags:

awk

perl

I have a tab delimited file(dummy) that looks like this :

a  b
a  b 
a  c
a  c
a  b

I am trying to write an awk command inside the perl script in which the file.txt is being made.

The awk command :

$n=system(" awk -F"\t" '{if($1=="a" && $2=="b") print $1,$2}' file.txt|wc -l ")

Error :
comparison operator :error in '==' , ',' between $1 and $2 in print }'

The awk script is running fine on command line but giving error while running inside the script.

I don't see any syntax error in the awk command.

like image 539
user1021713 Avatar asked Feb 11 '26 23:02

user1021713


2 Answers

Aside from the fact that what are you trying to achieve by executing awk from within perl (since it could be accomplished using the latter itself), you could use the q operator:

$cmd = q(awk -F"\t" '{if($1=="a" && $2=="b") print $1,$2}' file.txt | wc -l);
$n = system($cmd);

Note that using double-quotes would interpolate variables and you'd need to escape those.

like image 91
devnull Avatar answered Feb 13 '26 17:02

devnull


You can get the number of a\tbs from Perl itself without calling an external command:

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

open my $FH, '<', 'file.txt' or die $!;
my $n = 0;
"a\tb\n" eq $_ and $n++ while <$FH>;
print "$n\n";
like image 41
choroba Avatar answered Feb 13 '26 15:02

choroba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!