26

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.

2 Answers 2

35

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.

0
13

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.

1
  • 2
    This also requires the -e flag if you are writing the entire program on the command line. (otherwise it will fail to find the Perl script entitled "s/\./\@/g") Feb 7, 2012 at 10:19

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.