I recently came across the following two examples

Example 1: List only directories

ls -l | grep "^d"

Example 2: Search inside files

   ls | xargs grep -i "Find Some String"

Now i have read from here that

If you just use a pipe, it receives data on STDIN (the standard input stream) as a raw pile of data that it can sort through one line at a time.

So now I am a little confused as to why grep requires xargs in the second one and not in the first one. From what I understand so far is that xargs is used for converting stdin into arguments. (Since some programs require arguments instead of stdin). Does this mean grep can take both stdin and arguments ? I would appreciate it if some one could explain why is xargs used in the second example why cant it work without xargs? What purpose is it serving ?


In example 2 , you are searching for a certain text in the file contents, so you need xargs to pass the file names to grep.
In example 1, you are searching the output of ls, not the file contents.

actually, you can search file content without using xargs, which is better:

grep -i 'some text' *
| improve this answer | |
  • I just updated my question. Could you kindly add a little more detail. Thank you for explaining. – Rajeshwar Dec 28 '15 at 3:43
  • could you tell me what xargs is doing ? Does it convert stdout to arguments ? – Rajeshwar Dec 28 '15 at 4:47
  • yes, that's what xargs does, convert stdout to arguments. in your example, ls prints out file names, and grep need file names as arguments(not stdin), that's when xargs comes into play. You do need to understand that grep can work on both stdin and files. – SparedWhisle Dec 28 '15 at 5:23
  • so grep basically accepts parameters as stdin and also as parameters. If its parameters then grep expects those to be filenames is that correct ? – Rajeshwar Dec 28 '15 at 5:25
  • yes, grep expects its arguments as filenames, and it expects stdin as the content to work on. – SparedWhisle Dec 28 '15 at 5:27

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.