[lug] perl/awk question

Tkil tkil at scrye.com
Fri May 19 00:38:34 MDT 2000


>>>>> "arnie" == arnie  <asherman1 at uswest.net> writes:

arnie> I have a perl script where I need to extract a particular field
arnie> from the output of ps. At the command line, if I issue the
arnie> command:

arnie> | ps -ef | grep arnie | grep -v grep | awk '{print $6}'

arnie> I get the expected results, in this case all of the contents of
arnie> the sixth fields from ps. However, if I try to do this in perl
arnie> like this:

arnie> | @grep_array = `ps -ef | grep arnie | grep -v grep | awk '{print $6}'`;
arnie> | print @grep_array;

arnie> then the output is all of the fields returned from ps, as if
arnie> the awk is never executed. I have tried escaping the ticks and
arnie> curly braces, but it didn't work. How can I correct this so I
arnie> get only the specified field(s) into my array?

learn to use "-w" when you run with perl, and you will perhaps be
enlightened.  hint:  the single quotes inside the backquotes do *not*
protect their contents from double-quote expansion within the
backquotes.

also, since you're firing off perl anyway, you might as well just do
it all in perl (except for the "ps"; there's no good portable way to
do it, although linux-only you can probably use something in /proc)

something like:

  my %ttys = map { my @f = split; $f[0] eq 'tkil' ? ( $f[5] => 1 ) : () } 
               `/usr/bin/ps -ef`;
  my @ttys = sort keys %ttys;

or even:

  my %ttys;
  my @ttys;
  foreach (`/usr/bin/ps -ef`)
  {
    my ($user, $tty) = (split)[0,5];
    push @ttys, $tty if $user eq 'tkil' && !$seen{$tty}++;
  }

which maintains order.  both of them do a uniquify.  if you don't need
a uniquify, the easiest way i can think of to get the full list of
ttys matching that username would be:

  my @ttys = map { (split)[5] } grep { /^tkil/ } `/bin/ps -ef`;

you get the idea.  of course, if you're just trying to find out what
tty you are currently on, just use the "tty" command:

| $ tty
| /dev/ttyp0

and i think that has a /proc equivalent ... well, not directly, but if
you look at /proc/self/fd, you will see what devices your various file
descriptors are connected to.

anyway.  moral of the story:  use -w and "use strict" almost all the
time.

t.




More information about the LUG mailing list