Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I have a file with two columns separated by spaces like this:

potato 5
apple 7
pretzel 9

I want to issue a command on each line like this:

cmd -f potato -n 5
cmd -f apple -n 7
cmd -f pretzel -n 9

Can I get xargs to split the incoming line and pass those arguments to a command? Is xargs even the right command to use here?

share|improve this question
add comment

2 Answers

I don't think you can do that directly with xargs, but there's another solution :

$ cat /tmp/l
potato 5
apple 7
pretzel 9

using printf:

$ printf 'cmd -f %s -n %s\n' $(</tmp/l)
cmd -f potato -n 5
cmd -f apple -n 7
cmd -f pretzel -n 9

if you need to execute it, you can use another pipe to the shell, like

$ printf 'cmd -f %s -n %s\n' $(</tmp/l) | bash

Another simple & pure awk solution :

$ awk '{print "cmd -f "$1" -n "$2}' /tmp/l
cmd -f potato -n 5
cmd -f apple -n 7
cmd -f pretzel -n 9

Finally :

$ awk '{system("cmd -f "$1" -n "$2)}' /tmp/l
share|improve this answer
add comment

If you have GNU Parallel http://www.gnu.org/software/parallel/ installed you can do this:

cat food.txt | parallel --colsep ' ' cmd -f {1} -n {2}

It will also run one cmd per cpu core in parallel.

You can install GNU Parallel simply by:

wget http://git.savannah.gnu.org/cgit/parallel.git/plain/src/parallel
chmod 755 parallel
cp parallel sem

Watch the intro videos for GNU Parallel to learn more: https://www.youtube.com/playlist?list=PL284C9FF2488BC6D1

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.