views:

155

answers:

2

I have a perl script that writes out an array filled with integers to stdout, each on a separate line. So I would get output like:

412
917
1
etc

What I would like to do is be able to pipe the output of this script into xargs, and make a curl call using each integer. Something like this:

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

Below is an excerpt of a simple script I am using.

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);

However, this doesn't work the way I would expect. When I run the following command:

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

I get the output:

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

Is there anything special I need to do to use the output of a perl script in xargs?

Thanks

+3  A: 

Add -n 1 to xargs to make it eat only one argument on each run.

Micah Yoder
Great, worked like a charm. Thanks
Steve
+4  A: 

xargs doesn't use $1 like that. $1 is blank, and xargs just puts the numbers at the end of the command line.

You probably want to use a bash for loop like:

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

Which can be written on one line with semi-colons:

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

Note that you don't need cat:

cat [file] | script.foo

Is equivalent to:

script.foo < [file]
rjmunro
Great advice. Thank you.
Steve