Wednesday, February 17, 2016

Linux: Proper use of xargs

Credit: http://www.humans-enabled.com/2012/06/how-to-use-xargs-to-grep-or-rm-million.html


A CORRECT way to use xargs with grep:


$ find . -type f -print0 | xargs -0 grep 'rubies'


./file-78432:rubies diamonds and gold

In the above example, the find command checks the current directory for files of type and formats the output, replacing blank spaces in names with the null character (-print0), which then gets piped to the xargs command. The xargs command accepts the output from the find command, while ensuring no blank spaces with the -0 (format of -print0 command required), and greps the results for 'rubies'. As you can see in the output, this is how it's supposed to work.




The WRONG way to use xargs with grep


$ find . -type f | xargs -0 grep 'rubies'

xargs: argument line too long
In the above example, when the find command encounters our filename with 3 spaces in it, they are piped into the xargs command as 3 arguments at once, which causes an error because our xargs command only expects 1 argument.

No comments:

Post a Comment