如何从Perl脚本的每一行输出运行curl命令?

时间:2009-11-16 12:29:54

标签: unix command-line find

我有一个perl脚本,它将一个填充了整数的数组写入stdout,每个都在一个单独的行上。所以我会得到如下输出:

412
917
1
etc

我想要做的是能够将此脚本的输出传递给xargs,并使用每个整数进行curl调用。像这样:

cat input.json | ./jsonValueExtracter.pl -s exampleId | xargs curl http://brsitv01:8080/exampleId/$1 > example$1.json

以下是我正在使用的简单脚本的摘录。

my @values;
while(<STDIN>) {
     chomp;
     s/\s+//g; # Remove spaces
     s/"//g; # Remove single quotes
     push @values, /$opt_s:(\w+),?/g;
}

print join(" \n",@values);

但是,这不符合我的预期。当我运行以下命令时:

cat input.json | perl jsonValueExtracter.pl -s exampleId | xargs echo http://brsitv01:8080/exampleId/$1

我得到了输出:

http://brsitv01:8080/exampleId/ 412 917 1

在xargs中使用perl脚本的输出需要做些什么特别的事情吗?

由于

2 个答案:

答案 0 :(得分:5)

将-n 1添加到xargs以使其在每次运行时只吃一个参数。

答案 1 :(得分:5)

xargs不会像这样使用$ 1。 $ 1为空,xargs只是将数字放在命令行的末尾。

您可能希望使用bash for循环:

for i in `./jsonValueExtracter.pl -s exampleId < input.json`
do
  curl http://brsitv01:8080/exampleId/$i > example$i.json
done

可以用分号写在一行:

for i in `./jsonValueExtracter.pl -s exampleId < input.json`; do curl http://brsitv01:8080/exampleId/$i > example$i.json; done

请注意,您不需要cat:

cat [file] | script.foo

相当于:

script.foo < [file]