[英]perl - redirect system command to a file
I have this perl code below, basically want to loop through these 2 files. 我下面有这个perl代码,基本上想遍历这2个文件。 Then call a bash script (it takes the file and a delimiter as arguments and it prints out multiple lines) and then save all output from that command into a new file (with filename having '_processed' tacked on the end).
然后调用bash脚本(它将文件和分隔符作为参数,并打印出多行),然后将该命令的所有输出保存到新文件中(文件名的末尾加上“ _processed”)。 What is wrong with the below syntax (at the moment it just creates a blank file)?
以下语法有什么问题(目前它仅创建一个空白文件)?
#!/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);
}
You can redirect the output of a terminal command by preceding it with > <file name>
. 您可以在终端命令的输出之前加上
> <file name>
来重定向输出。 Ergo: Ergo:
system("sh myBashScript.sh $files[$i]");
Becomes: 成为:
system("sh myBashScript.sh $files[$i] > file.txt");
You seem to be confused with how perl writes to files. 您似乎对perl如何写入文件感到困惑。 Your
open
and close
on the MYFILE
handle will only create an empty file. 您在
MYFILE
句柄上的open
和close
将仅创建一个空文件。 system
does not do anything to that file within perl. system
在perl中不对该文件执行任何操作。 (Though I cannot say what your sh-script does with it). (尽管我不能说出您的sh脚本是如何处理的)。
Some pointers: 一些指针:
@files
instead of the elements, which reduces readability for no reason, since the indexes themselves are not used anywhere. @files
的索引而不是元素,这会无缘无故地降低可读性,因为索引本身并未在任何地方使用。 split
to extract file name and extension, and I assume there's a reason for that. split
提取文件名和扩展名,我认为这是有原因的。 However, there's no need to set LIMIT to 2, since you are only ever using the first one or two elements from that split. \\s
), the brackets are not needed. \\s
),则不需要括号。 So, use \\s
instead of [\\s]
. \\s
代替[\\s]
。 open
with a lexical file handle. open
。 system
only returns the return value of the system call. system
仅返回系统调用的返回值。 dunsmoreb is correct that you can simply redirect in the shell to create the file, but this is how it's done inside perl. If I were to guess, I'd say you were trying to write the output of the bash script to the file you are attempting to open, in which case you should do: 如果我猜到了,我会说您正在尝试将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.