Difference b/w xargs and "-exec" in Find

Hi,

What is the difference between the following commands

find . -type f -exec grep 'abc' {} \;

and

find . -type f | xargs grep 'abc'

Appreciate your help.

In the first, find will execute grep for each file found. This works well with any filename.

In the second, find will just print all the files to stdout. You then pipe this output into xargs. xargs reads from stdin and builds a command line. That command line will include more than 1 file.

So it may seem more efficient, but xargs does not handle filenames with whitespace (Unless GNU xargs with -0). find does offer a way to execute with more than 1 filename per invocation. It's find . type -f -exec grep 'abc' {} +

1 Like

Note also that xargs has some side-effects. It will split on spaces, and eat quotes. Usually you don't find either in filenames, but sometimes you do. You can disable this behavior in various ways depending on the system.

1 Like