rajsai28 has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

As i mentioned in the title, i need to execute some unix commands on the files which i read from the directory

sub zPrivateSub { my $dir = $OUTPUT_DIR; my $pattern = 'Jun'; opendir( DIR, $dir ); my @files = grep( /$pattern/, readdir(DIR) ); closedir(DIR); foreach my $file (@files) { if ($file=~ m/orig/) { my $lcmd = system("wc -l $file"); } else { print "NO\n";} } }

gives me this error message / faulty output:

orig_file.dat.gz wc: cannot open orig_file.dat.gz

please help me on this.

Thanks

  • Comment on How to Execute unix commands like "WC, tail, Gunzip, ZIP" against a file which is read from directory
  • Select or Download Code

Replies are listed 'Best First'.
Re: How to Execute unix commands like "WC, tail, Gunzip, ZIP" against a file which is read from directory
by smls (Friar) on Jun 06, 2013 at 04:37 UTC
    You either need to
    chdir($dir)
    before running the UNIX commands, or pass the full path to them like
    system("wc -l $dir/$file")
    .
Re: How to Execute unix commands like "WC, tail, Gunzip, ZIP" against a file which is read from directory
by soonix (Chancellor) on Jun 06, 2013 at 05:20 UTC

    Alternatively, instead of

    system("wc -l $file");
    you could do
    system("cd $dir; wc -l $file");
    which is less efficient, but if instead of wc you have another command, which works in the current directory, this might even be better.

    Of course, most efficient is chdir before you loop over the files (as suggested by smls)

      Hi Monks,

      Thanks for your valuable suggestion.

      i have used the below code and it works for me

      can we store the value of unix command in some variable because when we execute the unix command it will either return 0 or 1, i want to store the value

      chdir($dir); foreach my $file (@files) { if ($file=~ m/orig/) { my $lcmd = system("gunzip -c $file|tail -1"); }

      Output:

      123456|345627899292|000108418|

      i want to store the value 123456|345627899292|000108418| in variable so that i can use substr to fetch '000108418'

      Thanks a lot for the valuable inputs

      thanks & regards,
        Hi Monks,

        i got the syntax and please check below

        my $result = `gunzip -c $file|tail -1`;

        where i can get the unix command result

Re: How to Execute unix commands like "WC, tail, Gunzip, ZIP" against a file which is read from directory
by kcott (Archbishop) on Jun 06, 2013 at 06:32 UTC

    Except for some minor rewording, this is the same question you asked a matter of hours ago: "Reading file from the directory". I will be downvoting this node.

    -- Ken

      Hi, Yes true, i thought the the question what i asked was not clear so sent by chaning the description and using some format tips. regards,