![](/img/trans.png)
[英]Perl: tail file in background while running another system command in loop
[英]perl - redirect system command to a file
我下面有这个perl代码,基本上想遍历这2个文件。 然后调用bash脚本(它将文件和分隔符作为参数,并打印出多行),然后将该命令的所有输出保存到新文件中(文件名的末尾加上“ _processed”)。 以下语法有什么问题(目前它仅创建一个空白文件)?
#!/usr/bin/env perl
use strict;
use warnings;
my(@files) = (
"fixedtt.txt '|'",
"delimd2iffpipe.dat '|'"
);
for my $i (0 .. $#files) {
my($filename) = split /[\s]+/, "$files[$i]", 2;
my($name, $type) = split /[\.]+/, "$filename", 2;
open (MYFILE, '>'."$name".'_processed.'."$type");
system("sh myBashScript.sh $files[$i]"); #I want to write the entire output of this command to a file
close (MYFILE);
}
您可以在终端命令的输出之前加上> <file name>
来重定向输出。 Ergo:
system("sh myBashScript.sh $files[$i]");
成为:
system("sh myBashScript.sh $files[$i] > file.txt");
您似乎对perl如何写入文件感到困惑。 您在MYFILE
句柄上的open
和close
将仅创建一个空文件。 system
在perl中不对该文件执行任何操作。 (尽管我不能说出您的sh脚本是如何处理的)。
一些指针:
@files
的索引而不是元素,这会无缘无故地降低可读性,因为索引本身并未在任何地方使用。 split
提取文件名和扩展名,我认为这是有原因的。 但是,由于您仅使用该拆分中的前一个或两个元素,因此无需将LIMIT设置为2。 \\s
),则不需要括号。 因此,使用\\s
代替[\\s]
。 open
。 system
仅返回系统调用的返回值。 dunsmoreb是正确的,您可以直接在shell中重定向以创建文件,但这是在perl中完成的。 如果我猜到了,我会说您正在尝试将bash脚本的输出写入尝试打开的文件,在这种情况下,您应该这样做:
my @files = (
"fixedtt.txt '|'",
"delimd2iffpipe.dat '|'"
);
for my $args (@files) {
my ($filename) = split ' ', $args;
$filename =~ s/\./_processed./;
open my $fh, '>', $filename or die $!;
print $fh qx(sh myBashScript.sh $args);
close $fh;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.