Tiny Code

Tiny Code

Sunday, January 20, 2013

Unix tool: xargs

One of the reasons I like Unix style operating systems so much is the Unix Philosophy.  One of the principles is it's better to include a bunch of small, fast tools which can be combined together to accomplish a variety of tasks than it is to build large special purpose tools which are complicated to use.  One of my favorite of these Unix tools is xargs.  What xargs is good at is taking a bunch of separate lines of input and changing those into arguments for another command.

Perhaps an example will serve to illustrate better than a dry explanation.

Let's imagine we want to find all the source files from the current directory (recursively) which contain the string "stdio.h" and to edit each of those files using vi.  The following line will accomplish that.  Of course in Unix, there are numerous ways to accomplish the same task.  This happens to be my favorite way to perform the task and serves to illustrate the use of xargs nicely.

find . -name "*.c" -print | xargs grep -l "stdio.h" | xargs vi

The first part of the command (that before the first pipe character) is a simple find command.  The only thing worthy of explanation is the quotes around the file pattern.  Unix shells will substitute matches for a wildcard such as this before the find command gets invoked.  If we invoke this long command in a directory containing files which match the pattern *.c, the matches would be substituted on the command line instead of the actual *.c pattern.

The second part of the command is a simple grep command but combined with the xargs command.  This passes the file names output by the find command to be used as arguments to the grep command.  The grep command is looking for files which contain the string "stdio.h", a common c library header file.

The third part of the command simply takes the matching files found by grep and passes them to vi.

This example should work on either Linux or Mac OS X.  It will also work on Windows provided you've installed a Unix environment such as Cygwin.  Cygwin is one of the first things I install on any Windows machine I have to use on more than a casual basis.

Play around with the xargs command to get a feel for what it can do.  It's a handy part of any Unix tech's grab bag of tricks.

No comments: