如何将 Bash Shell 命令的输出逐行传送到 Perl 以进行正则表达式处理?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9174206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 21:38:02  来源:igfitidea点击:

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

perlbashpipe

提问by user1129812

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 命令的输出数据。输出用“\n”或“\0”逐行分隔。我想知道有什么方法可以将输出通过管道传输到 Perl 并在 Perl 中逐行处理数据(就像将输出管道传输到 awk,但在我的情况下它是在 Perl 上下文中。)。我想命令可能是这样的:

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.

假设我想在“逐行”的基础上将所有“:”字符替换为“@”字符(不是全局替换,我可以使用条件,例如奇数行或偶数行,以确定当前行是否应该具有替换与否。),那么我怎么能做到这一点。

回答by daxim

See perlrun.

请参阅perlrun

perl -lpe's/:/@/g'      # assumes \n as input record separator
perl -0 -lpe's/:/@/g'   # assumes ##代码## 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.

是的,Perl 可以出现在管道中的任何地方,就像 awk 一样。

回答by Alien Life Form

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:

命令行开关 -p(如果您想要自动打印)或 -n(如果您不想要)将执行您想要的操作。行内容在 $_ 中,所以:

perl -pe's/\./\@/g'

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.

将是一个解决方案。通常,您想阅读“<>”(菱形)运算符,这是非单行者的方法。