user1129812
user1129812

Reputation: 2889

How to pipe Bash Shell command's output line by line to Perl for Regex processing?

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.

Upvotes: 26

Views: 25282

Answers (2)

daxim
daxim

Reputation: 39158

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.

Upvotes: 35

Alien Life Form
Alien Life Form

Reputation: 1944

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.

Upvotes: 13

Related Questions