Using `xarg` to pass to `find`

I just found myself needing to run wc -l on all the files in a list of directories – in my case, I had a big old list of directories with a matching name. But I wanted to calculate the total number of files in those directories.

Unfortunately, find is very particular about where its arguments go, so running xargs and passing it to find was resulting in the following:

find: paths must precede expression: tmp/dir/name
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]

Luckily, the solution is pretty simple. Use the -I flag to xargs to make it replace {} with your argument.

So your full command will look something like this:

cat list_of_directories.txt | xargs -I{} find {} | whatever

The command that I ended up with is this:

find . -name "dir_name" | xargs -I{} find {} -type f | wc -l

I hope that’s helpful for you.

(Reference: http://xion.io/post/code/shell-xargs-into-find.html)

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.