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...

1

3 Answers 3

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).

2
  • feel free to correct to array, a correct answer is worth more than a funny one. I'll remove the silly comments ;)
    – Konerak
    Commented May 17, 2011 at 6: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
    Commented May 17, 2011 at 6: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).

1
  • 1
    It is safer to use open(); It save some escaping.
    – J-16 SDiZ
    Commented May 17, 2011 at 7:23
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>);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.