Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using bash command in perl

Tags:

bash

awk

perl

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

like image 901
ibrahim Avatar asked May 17 '11 06:05

ibrahim


People also ask

How do you call a bash script in Perl?

Note: Here, once the bash script completes execution it will continue with the execution of the perl script. Below is a perl script “perl-script.pl” which calls an external bash script “bash-script.sh”. #!/usr/bin/perl use strict; use warnings; print "Running parent perl script.

How do you call a shell command in Perl?

We use the backticks ( `` ) syntax when we want to capture the output of the shell command. We provide the command between the backticks. If we don't want to capture the output of the shell command, we use the system function, as shown below. The system function will just display the output.

How do I run an exec in Perl?

exec - Perldoc Browser. The exec function executes a system command and never returns; use system instead of exec if you want it to return. It fails and returns false only if the command does not exist and it is executed directly instead of via your system's command shell (see below).


3 Answers

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

like image 135
Rafe Kettler Avatar answered Sep 26 '22 08:09

Rafe Kettler


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

like image 32
ADW Avatar answered Sep 24 '22 08:09

ADW


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>);
like image 22
TLP Avatar answered Sep 23 '22 08:09

TLP