5

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
  • This question gives some examples of how to call external programs in Perl. Commented May 17, 2011 at 6:24

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

Sign up to request clarification or add additional context in comments.

2 Comments

feel free to correct to array, a correct answer is worth more than a funny one. I'll remove the silly comments ;)
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?
8

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 Comment

It is safer to use open(); It save some escaping.
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>);

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.