0

I have a directory that contains the following

Applications  Desktop   Documents   Downloads   Dropbox (Personal)
Google Drive   Library   Movies   Music   Pictures   Public

I am trying to learn how to use grep by playing around with it, and uncovered the following surprising result when I piped the output of ls into grep:

ls | grep D* returns:

grep: Documents: Is a directory
grep: Downloads: Is a directory
grep: Dropbox (personal): Is a directory
grep: Google Drive: Is a directory

But when I do ls | grep Do* I get the following:

grep: Downloads: Is a directory

Why doesn't ls | grep Do* return the Documents folder as well? As in:

grep: Documents: Is a directory
grep: Downloads: Is a directory

Lastly, this question is different than the questions and answers here and here. I'm not looking for a way to solve this problem by switching to awk or passing flags to grep: instead, I'm looking to understand the underlying behavior of grep.

BLimitless
  • 2,060
  • 5
  • 17
  • 32

1 Answers1

1

But when I do ls | grep Do* I get the following:

That's because the Do* gets expanded by the shell into Documents Downloads Dropbox (Personal).

You're doing the grepping all wrong. If you want a filename that starts with D then you would do ls | grep ^D. grep uses regular expressions, not file globbing.

Also, you should not be using ls and grep to find files. If you want to find files that start with D then use find . -name 'D*'.

Andy Lester
  • 91,102
  • 13
  • 100
  • 152