6

i have short bash code

cat example.txt | grep mail | awk -F, '{print $1}' | awk -F= '{print $2}'

I want to use it in perl script, and put its output to an array line by line. I tried this but did not work

@array = system('cat /path/example.txt | grep mail | awk -F, {print $1} | awk -F= {print $2}');

Thanks for helping...

ibrahim
  • 3,254
  • 7
  • 42
  • 56
  • [This question](http://stackoverflow.com/questions/797127/whats-the-differences-between-system-and-backticks-and-pipes-in-perl) gives some examples of how to call external programs in Perl. – Nathan Fellman May 17 '11 at 06:24

3 Answers3

11

The return value of system() is the return status of the command you executed. If you want the output, use backticks:

@array = `cat /path/example.txt | grep mail | awk -F, {print \$1} | awk -F= {print \$2}`;

When evaluated in list context (e.g. when the return value is assigned to an array), you'll get the lines of output (or an empty list if there's no output).

Rafe Kettler
  • 75,757
  • 21
  • 156
  • 151
  • feel free to correct to `array`, a correct answer is worth more than a funny one. I'll remove the silly comments ;) – Konerak May 17 '11 at 06:31
  • I did it but this time awk is not working, it give only output of 'cat /path/example.txt | grep mail' , what should I do? – ibrahim May 17 '11 at 06:48
9

Try:

@array = `cat /path/example.txt | grep mail | awk -F, {print \$1} | awk -F= {print \$2}')`;

Noting that backticks are used and that the dollar signs need to be escaped as the qx operator will interpolate by default (i.e. it will think that $1 are Perl variables rather than arguments to awk).

ADW
  • 4,030
  • 17
  • 13
2

Couldn't help making a pure perl version... should work the same, if I remember my very scant awk correctly.

use strict;
use warnings;

open A, '<', '/path/example.txt' or die $!;
my @array = map { (split(/=/,(split(/,/,$_))[0]))[1] . "\n" } (grep /mail/, <A>);
TLP
  • 66,756
  • 10
  • 92
  • 149