DarkMatter in Cyberspace
  • Home
  • Categories
  • Tags
  • Archives

xargs notes


Synopsis: xargs <command> <command options>

When you run <command> | xargs <command2> <cmd2-options>, and the result of (only) running is:

<cmd1-result-line1>
<cmd1-result-line2>
...

actually you are running:

<command2> <cmd2-options> <cmd1-result-line1>
<command2> <cmd2-options> <cmd1-result-line2>
...

If you want add before , you have to use -I options. Usually we use "%" as a placeholder. For example, echo '1\n2\n3' |xargs -n 1 echo ok produces:

ok 1
ok 2
ok 3

while echo '1\n2\n3' |xargs -n 1 -I % echo % ok produces:

1 ok
2 ok
3 ok

Here "-n 1" means the maximum number of arguments is 1 in every command line.

So echo '1\n2\n3'|xargs -n 2 echo ok produces:

ok 1 2 
ok 3

The following command gives the total lines of java code under current directory (and subdirectories):

find . -name '*.java'|xargs wc -l

while

find . -name '*.java'|wc -l

produces how many java files under current directory (and subdirectories).

Note: the quotes of "*.java" is necessary.

Ref: http://offbytwo.com/2011/06/26/things-you-didnt-know-about-xargs.html



Published

Sep 5, 2013

Last Updated

Dec 14, 2018

Category

Tech

Tags

  • linux 158
  • shell 46
  • xargs 1

Contact

  • Powered by Pelican. Theme: Elegant by Talha Mansoor