Friday, January 28, 2005
Geeky Friday: find, xargs, grep, and spaces
On linux/unix systems, the find command is often used along with grep to find text in a file somewhere in a multi-level directory hierarchy. Two ways to do this are:
find . -type f -exec grep "blah" {} \;
find . -type f -print | xargs grep "blah"
The second method is slightly better as the grep command will be run only once on all files found whereas the first will run grep for each file.The second method breaks down if find finds filenames containing spaces. If, for example, there's a file named "How To Conquer The World.txt". The xargs grep part will try to search in five files: "How", "To", "Conquer", "The", "World.txt" and grep will complain that these files don't exist.
But wait, it's 2005, surely the geeks of the world have resigned themselves to the fact that some people like to put spaces in file names -- not out of malice towards linux geeks, but just because they don't know what it can do. The good news is that yes, in fact, the geeks working on find and xargs have done something about this.
Their solution is to provide an alternate file name delimiter. The new way to handle this is to do this:
find . -type f -print0 | xargs -0 grep blahThe -print0 tells find to output its list of files separated by nul (ASCII 0) instead of a space. Similarly, the -0 tells xargs to expect that its input is separated by nulls
Archives
* June 2001 * July 2001 * August 2001 * September 2001 * October 2001 * November 2001 * December 2001 * January 2002 * February 2002 * March 2002 * April 2002 * May 2002 * June 2002 * July 2002 * August 2002 * September 2002 * October 2002 * November 2002 * December 2002 * January 2003 * February 2003 * March 2003 * April 2003 * May 2003 * June 2003 * July 2003 * August 2003 * September 2003 * October 2003 * November 2003 * December 2003 * January 2004 * February 2004 * March 2004 * April 2004 * May 2004 * June 2004 * July 2004 * August 2004 * September 2004 * October 2004 * November 2004 * December 2004 * January 2005 * February 2005 * March 2005 * April 2005 * May 2005 * June 2005 * July 2005 * August 2005 * September 2005 * October 2005 * November 2005 * December 2005 * January 2006 * February 2006 * March 2006 * April 2006 * May 2006 * June 2006 * August 2006 * September 2006 * November 2006 * March 2007 * April 2007 * August 2007 * September 2007


