Piping find to xargs handling spaces

Posted on Wednesday, September 18, 2013


Piping find to xargs handling spaces


The find command already has an exec option that allows you to execute a command on the list of files you find.  As an example you can do the following command.


> find . -iname "*.avi" -exec ls -alh {} \;


This would list all the files ending in .avi  (ignoring case) then run ls -alh on each one.


exec has some limitations and it also feels clucky when I have to add a \; at the end.

A better option is to pipe the output to another the xargs command.  This same command sent to xargs would be



> find . -iname "*.avi" | xargs ls -alh {}


This command almost works.  The problem is that I need the full path of the files I and get the local ones.

To fix this run this command



> find $PWD -iname "*.avi" | xargs ls -alh "{}"


Using $PWD or `pwd` will search and return the local absolute path.  Find will return the full path if you search on the full path.

However there is a problem with this, at least for me.  I am actually searching an iPhoto directory for .avi files to convert.   OSX has many directories with spaces in their names and the prior command does not work with spaces.  If you have spaces run this command.




> find "$PWD" -iname "*.avi" | xargs -I{} ls -alh "{}"


The Quotes around $PWD take care of the spaces for the output and the -I{}  allows xargs to handle the spaces handed to xargs.







References
[1]        How can I use xargs to copy files that have spaces and quotes in their names?
            Comment by    the_mint

                Accessed 09/2013 

No comments:

Post a Comment