in reply to Redirect a substring/desired values from a System output to a file in Perl

Hello Murali_Newbee and welcome to the monastery and to the wonderful world of Perl!

You can use open using the pipe | at the end of the command to read from a command output and then parse each line.

Like in:

open my $cmd, "/bin/cmd|" or die "something useful here like $^E"; while (<$cmd>){ chomp; print $append_file "$1\n" if $_ =~ /_id:(\S)+$/; #please re-check t +he regex.. }

L*

PS in the same way you can write to a program STDIN putting the pipe in front of the program like open my $sendmail, "|/usr/sbin/sendmail etc etc";

The above example is the basic way to do what do you ask for but many modules on cpan can achieve the same in different, perhaps more robust, way.

Also note that you can open your append file once and outside of the loop: you reopen it many times and you profit of the automatic close when $file goes out of the scope: do not take this habit! use the explicit close as soon as you do not need the filehandle anymore.

More: if you just want to append to a single file during all the program you can use select $filehandle to have all print calls redirected to such file.

L*

There are no rules, there are no thumbs..
Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.

Replies are listed 'Best First'.
Re^2: Redirect a substring/desired values from a System output to a file in Perl
by Murali_Newbee (Novice) on Jul 31, 2018 at 14:40 UTC
    Hi Discipulus, with my previous script i achieved the output to the file i mentioned, the problem here is i get the bunch of output, where i need an id, could you please help me with the Regular expression?