gpt4 book ai didi

perl - 如何在命令行中使用 Perl 来搜索其他程序的输出?

转载 作者:行者123 更新时间:2023-12-04 13:10:29 24 4
gpt4 key购买 nike

据我所知(Perl 对我来说是新手)Perl 可用于针对 Unix 命令行编写脚本。我想要做的是运行(硬编码)命令行调用,并在这些调用的输出中搜索 RegEx 匹配项。有没有办法在 Perl 中简单地做到这一点?如何?

编辑:这里的顺序是:
- 调用另一个程序。
- 针对其输出运行正则表达式。

最佳答案

my $command = "ls -l /";
my @output = `$command`;
for (@output) {
print if /^d/;
}
qx//准引用运算符(反引号是快捷方式)从 shell 语法中窃取:在新 shell 中将字符串作为命令运行,并返回其输出(作为字符串或列表,取决于上下文)。见 perlop详情。

您还可以打开管道:
open my $pipe, "$command |";
while (<$pipe>) {
# do stuff
}
close $pipe;

这允许您 (a) 避免将整个命令的输出一次收集到内存中,并且 (b) 使您可以更好地控制运行命令。例如,您可以避免命令被 shell 解析:
open my $pipe, '-|', @command, '< single argument not mangled by shell >';

perlipc有关更多详细信息。

关于perl - 如何在命令行中使用 Perl 来搜索其他程序的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/469941/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com