I have some output data from some Bash Shell commands. The output is delimited line by line with "\n" or "\0". I would like to know that is there any way to pipe the output into Perl and process the data line by line within Perl (just like piping the output to awk, but in my case it is in the Perl context.). I suppose the command may be something like this :
Bash Shell command | perl -e 'some perl commands' | another Bash Shell command
Suppose I want to substitute all ":" character to "@" character in a "line by line" basis (not a global substitution, I may use a condition, e.g. odd or even line, to determine whether the current line should have the substitution or not.), then how could I achieve this.
Perl's open function opens a pipe instead of a file when you append or prepend a pipe symbol to the second argument to open . This turns the rest of the arguments into a command, which will be interpreted as a process (or set of processes) that you want to pipe a stream of data either into or out of.
In addition, if you just want to process a command's output and don't need to send that output directly to a file, you can establish a pipe between the command and your Perl script. use strict; use warnings; open(my $fh, '-|', 'powercfg -l') or die $!; while (my $line = <$fh>) { # Do stuff with each $line. }
From Perl HowTo, the most common ways to execute external commands from Perl are: my $files = `ls -la` — captures the output of the command in $files. system "touch ~/foo" — if you don't want to capture the command's output. exec "vim ~/foo" — if you don't want to return to the script after executing the command.
A pipe in Bash takes the standard output of one process and passes it as standard input into another process. Bash scripts support positional arguments that can be passed in at the command line. Guiding principle #1: Commands executed in Bash receive their standard input from the process that starts them.
See perlrun.
perl -lpe's/:/@/g' # assumes \n as input record separator perl -0 -lpe's/:/@/g' # assumes \0 as input record separator perl -lne'if (0 == $. % 2) { s/:/@/g; print; }' # modify and print even lines
Yes, Perl may appear at any place in a pipeline, just like awk.
The command line switch -p (if you want automatic printing) or -n (if you don't want it) will do what you want. The line contents are in $_ so:
perl -pe's/\./\@/g'
would be a solution. Generally, you want to read up on the '<>' (diamond) operator which is the way to go for non-oneliners.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With