【问题标题】:How can I run a curl command for each line of output from my Perl script?如何为 Perl 脚本的每一行输出运行 curl 命令?
【发布时间】:2009-11-16 12:29:53
【问题描述】:

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

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 脚本的输出,我需要做些什么特别的事情吗?

谢谢

【问题讨论】:

  • 注意:cat的无用用法:perl jsonValueExtracter.pl -s exampleId &lt; input.json | xargs ...

标签: unix command-line find


【解决方案1】:

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]

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-18
      • 1970-01-01
      • 2011-05-31
      • 1970-01-01
      • 2016-02-20
      • 2011-03-14
      • 2014-04-11
      • 1970-01-01
      相关资源
      最近更新 更多