27

Suppose you are in a directory that contains many files and many subdirectories.

You want to get a directory listing of all the files beginning with the letter "d". You type

ls d*

and what you get back is mostly files in sub-directories (in particular, files in subdirectories that begin with "d").

How do you list only the files and directory names in your current directory?

5 Answers 5

39

Ah, I just found it on the 6th reading of the man page. It's the not-so-sensibly named "directory" parameter

ls -d d* 
7
  • 7
    It took you just 29 seconds to re-read the man page and write up this answer? That's quick :-)
    – balpha
    Aug 19, 2009 at 18:14
  • 1
    Additionally, ls -d d*/ will only show the directories.
    – innaM
    Aug 19, 2009 at 19:00
  • 7
    balpha - I discovered it before submitting the question, then realized that if it took me so long to figure this out, I might as well help a future searcher out and post the q and a here.
    – dggoldst
    Aug 20, 2009 at 12:35
  • 3
    Fair enough; there's nothing wrong with it.
    – balpha
    Aug 20, 2009 at 12:44
  • 1
    And yet, CppLearner, it does indeed work. Try it.
    – dggoldst
    Sep 28, 2013 at 16:51
10

I believe another interesting solution to be,

ls | grep ^d

Offers the flexibility of regular expressions.

4
  • 3
    And the complexity of regular expressions! ;-)
    – Chris Nava
    Aug 19, 2009 at 20:02
  • 1
    That is an interesting soln, and I like the idea of using regexs, however, if you add additional parameters to ls it will break. E.g. "ls -l | grep ^d"
    – dggoldst
    Aug 20, 2009 at 12:41
  • True, but not all parameters. ls -a | grep "^\." would print all "hidden" files.
    – Kuer
    Aug 20, 2009 at 13:31
  • other ls flags do not work when using this approach. e.g. ls -ltr | grep ^d doesn't work. while the one suggested in @dggoldst answer does. Mar 12, 2015 at 7:36
4

find . -maxdepth 1 -name d* -type f

Okay, using find here is a tad of overkill. Just a tad.

1
  • 1
    But it helped me list all direct directories of a specific user : find /home/ -maxdepth 1 -type d -user www-data. So thanks, and +1
    – Cyril N.
    Sep 4, 2012 at 13:01
1

ls -ld: It will give the list of directories, without descending into subdirectories.

Example:

ls -ld Cust*
This command will provide a listing of the files and directories which start with Cust.

1
1

ls -a | grep "^."

ls -a: it will demonstrate all files and folders (hidden files and unhidden files together)

grep "^.": it will filter the result, and it will choose to show you just the files starts with a point.

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.