http://qs321.pair.com?node_id=11108773


in reply to How to awk a grep result in-script

Hi, ShipWreck

Here are Perl snippets resembling awk and grep. The open statement emits a warning to the terminal if the command doesn't exist. Thus the reason simply exiting with status 127 matching the status in shell.

Shell

$ ps -ef | awk '{ print $1,$2,$8 }' | grep '^kdfadm ' $ ps -ef | awk '{ if ($1 == "kdfadm") print $1,$2,$8 }'

Perl (no delays, fast like awk)

use strict; use warnings; $, = ' '; # set output field separator $\ = "\n"; # set output record separator open my $cmd, 'ps -ef |' or exit(127); while (<$cmd>) { my ($f1,$f2,undef,undef,undef,undef,undef,$f8) = split(' ',$_,-1); print $f1,$f2,$f8 if ($f1 eq 'kdfadm'); } close $cmd;

Perl using Proc::ProcessTable (suggestion by haukex and 1nickt)

use strict; use warnings; use Proc::ProcessTable; $, = ' '; # set output field separator $\ = "\n"; # set output record separator my $t = Proc::ProcessTable->new(); my $uid = getpwnam('kdfadm'); foreach my $p (@{ $t->table }) { print @{ $p }{qw( uid pid cmndline )} if ($p->uid == $uid); }

Regards, Mario