如何用逗号分隔从perl脚本返回的控制台输出

时间:2013-12-11 16:59:27

标签: perl bash

正如Igor Chubin在Call a bash script from a perl script中所述,从perl脚本中检索bash脚本结果的一种方法是:

    $result = `/bin/bash /path/to/script`;

现在,我的结果实际上是一系列文件,因为这个脚本运行一个简单的find命令。控制台上的结果如下:

    /path/to/file.extension
    /path/to/file2.extension

我想获取结果,删除空格,并连接用逗号分隔的文件名。所以我的$result看起来像:

    /path/to/file.extension,/path/to/file2.extension

最有效的方法是什么?请注意,这是在perl脚本中进行的。

3 个答案:

答案 0 :(得分:1)

 chomp($result);
 $result =~ tr|\n|,|; # replace every newline with comma
 $result =~ s|\s+||g; # remove whitespaces

答案 1 :(得分:1)

foreach my $file ( split(/\s+/,$result) ) {
    $file=~s/\s+//g;
    push(@array,$file);
}
print join(",",@array)

写完之后,我想提一下,如果你的脚本正在调用一个找到的shell脚本,我建议你查看File :: Find perl模块并在Perl中完成整个过程。

答案 2 :(得分:0)

你有一个这样的字符串:

file_list = "file_1
file_2
file_3
file_4"

并且您想将其更改为逗号分隔。

您可以使用splitjoin

 my $comma_separated_list = join ", ", split( /\n/, $nl_separated_file_list );

在两个单独的命令中(可能更容易看到):

my @file_array = split /\n/, $nl_separated_file_list;
my $comma_separated_list = join ", ", $nl_separated_file_list;

split将生成一个数组(每行一个。连接将生成一个逗号分隔的字符串。这里的示例将产生:

$ comma_separated_list =“file1,file2,file3,file4,...”;

如果您不想要空格,请在联接", "中将其保留。

可以使用正则表达式(用\n替换,的每个瞬间)来执行此操作,但我怀疑这比连接/拆分需要更长的时间。

相关问题