7
$ seq 1 3
1
2
3
$ seq 1 3 | xargs echo
1 2 3
$

Mentally replace seq 1 3 with any command that lists entries one-per-line on standard out. How can I get more-or-less what you'd expect, i.e. the entries on separate lines (echo 1; echo 2; echo 3;)?

  • Often is xargs not the command you need. You are using two external commands seq respectively xargs to achieve something that your shell can do it on it's own. Take for example Brace expansion in bash. You could then issue printf '%s\n' {1..10} to get the desired result – Valentin Bajrami Apr 12 '15 at 18:25
  • @val0x00ff My real use case is implementing a Brewfile for homebrew in my own bootstrap script. I'm not sure I can use any features of the shell to do the job. – Sean Allred Apr 12 '15 at 18:28
  • The function you have there nocomment and oneline could be combined into one function nocomment_oneline and put sed '/^#/d;/^.$/d' "$1" | sed -e :a -e '$!N;s/\n/ /;ta' – Valentin Bajrami Apr 12 '15 at 18:53
  • @val0x00ff Yes, but then I couldn't actually use it. – Sean Allred Apr 12 '15 at 18:54
  • I'm not sure why you wouldn't be able to? That just combines both functions. You are using one function to filter out comments and empty lines. After that you are reading the file and putting all lines in one. – Valentin Bajrami Apr 12 '15 at 19:02
14

Normally xargs will put several arguments on one command line. To limit it to one argument at a time, use the -n option:

$ seq 3 | xargs -n 1 echo
1
2
3

Documentation

From man xargs:

-n max-args
Use at most max-args arguments per command line. Fewer than max-args arguments will be used if the size (see the -s option) is exceeded, unless the -x option is given, in which case xargs will exit.

Difference between -n and -L

-L is similar but has an extra feature: unlike -n, lines with trailing blanks are continued onto the next line. Observe:

$ echo $'1 \n2\n3\n4'
1 
2
3
4
$ echo $'1 \n2\n3\n4' | xargs -L 1 echo
1 2
3
4
$ echo $'1 \n2\n3\n4' | xargs -n 1 echo
1
2
3
4
  • I wonder: how do -n and -L differ in terms of use-case? Surely they must differ outside of this trivial example. – Sean Allred Apr 12 '15 at 18:00
  • @SeanAllred -L differs in that it has a trailing blank feature. I just added an example illustrating it. (Your answer has my +1) – John1024 Apr 12 '15 at 18:05
  • 1
    I think Sean means, when would you use xargs -L? When is the trailing blanks feature useful? – Tor Klingberg Apr 13 '15 at 14:57
6

A bit more research revealed the answer from Make xargs execute the command once for each line of input:

$ seq 1 3 | xargs -L 1 echo
1
2
3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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