On Mac OSX
For simple cases that have a known number of args, tell xargs how many args to send to each command. For example
$ echo "1\n2\n3" | xargs -n1 echo "#"
# 1
# 2
# 3
When your input args are complex, and newline terminated, a better method is:
$ echo "1\n2 3\n4 5 6" | xargs -L1 echo "#"
# 1
# 2 3
# 4 5 6
There is a probem here, can you see it? What if our input line contains a single quote:
$ echo "1\n2 3\n4 '5 6" | xargs -L1 echo "#"
# 1
# 2 3
xargs: unterminated quote
xargs
does not like single quotes unless you use the -0
flag. But -0
and -L1
are not compatible, so that leaves us with:
$ echo "1\n2 3\n4 '5 6" | tr '\n' '\0' | xargs -0 -I{} echo "#" {}
# 1
# 2 3
# 4 '5 6
If you brew install findutils
we can do a little better:
$ echo "1\n2 3\n4 '5 6" | gxargs -d\\n -i echo "#" {}
# 1
# 2 3
# 4 '5 6
But wait, maybe using xargs
is just a bad tool for this one. What if we use the shell builtins instead:
$ echo "1\n2 3\n4 '5 6" | while read -r; do echo "# $REPLY"; done
# 1
# 2 3
# 4 '5 6
For some more thoughts about xargs
vs while
checkout this question.