xargs split incoming line

3

4

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?

wonk wonk

Posted 2012-03-15T23:16:44.193

Reputation: 73

Answers

3

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

Gilles Quenot

Posted 2012-03-15T23:16:44.193

Reputation: 3 111

works great and is simple enough that I can hope I'll eventually remember it... my question is, any easy modification to convert this working example echo 11 22 | awk '{print "echo -f "$1" -n "$2}' to have a CSV line input instead of space-delimited, like this: echo 11,22 ? – nmz787 – 2019-08-29T01:53:43.083

2

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

Ole Tange

Posted 2012-03-15T23:16:44.193

Reputation: 3 034