Chamara Keragala Chamara Keragala - 3 months ago 21
Perl Question

Define a perl variable inside AWK statement

I have defined a perl variable inside the awk script.

my $max = 76500;
my $uidNumber = `ypcat passwd | cut -d ":" -f3 | awk -v var=\$max '\$NF >= 76000 && \$NF <= \{print var\}' | sort -n`;
print $uidNumber


I get below error when I run the script

awk: $NF >= 76000 && $NF <= {print var}
awk: ^ syntax error


Works perfectly when the varible is not defined

my $uidNumber = `ypcat passwd | cut -d ":" -f3 | awk '\$NF >= 76000 && \$NF <= 76500' | sort -n`;
print $uidNumber

Answer

OK, so my first answer would be: Don't.

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

open ( my $passwd_file, '<', 'passwd' ) or die $!; 

while ( <$passwd_file> ) { 
    chomp;
    my ( $username, $x, $uid, @rest ) = split /:/;
    print $uid,"\n" if $uid >= 76000 and $uid <= 76500;
}

That's not sorted, it's just in 'passwd file' order it'll print. I'm not clear what you're actually looking for, because you sort at the end - so will have a string with a load of numbers in it.

But maybe something like this is what you'd want?

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


open ( my $passwd_file, '<', 'passwd' ) or die $!; 

my @uids; 
while ( <$passwd_file> ) { 
    chomp;
    my ( $username, $x, $uid, @rest ) = split /:/;
    push ( @uids, $uid ) if $uid <=76500 and $uid >= 76000; 
}

print join "\n", sort { $a <=> $b } @uids;

Note - as you mention in the comments it's a ypcat command:

open ( my $input, '-|', 'ypcat passwd' ); 

And then do the same thing.

Sorting the list and printing last element:

print "UID:", (sort { $a <=> $b } @uids )[-1],"\n";