I know a command that I use pretty often when working on someone else's code base, here is an example

find ./ -name "*.php" | xargs grep "my_awesome_function("

I have already read through the docs on each of the commands here as find, pipe, xargs and grep from http://www.computerhope.com/unix.htm

Yet I still don't entirely understand how this command searches for every php file from current directory down and then looks for which of them contain a string "my_awesome_function(". I understand how pre pipe part works, but after the pipe my understanding vanishes. I get that each file is sent like an argument to the grep command, can someone explain what is happening here?


Try executing the find command without the last part:

find ./ -name "*.php"

What you'll see is a list of filenames, all ending with .php.

Now the xarg commands reads all these filenames from the pipe, takes a bunch of them (you can set how many using option -n 2), and then calls its argument with these names. So if the output of find is file1.php file2.php file3.php, and xarg would group at most two files together (or you force it to with xargs -n 2), then it would call

grep "my_awesome_function(" file1.php file2.php
grep "my_awesome_function(" file3.php

which in turn produces your output. You can see what is really going on by inserting an echo:

find ./ -name "*.php" | xargs echo grep "my_awesome_function("

Also play around with the grouping:

find ./ -name "*.php" | xargs -n 2 echo grep "my_awesome_function("

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.