Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

Is it possible to get only the results from find that are directory paths? Using find with some option, or using grep or some other utility the results are piped into as a filter?

I thought something like find | grep */$ might work, but it doesn't. From some other testing where I "grepped for" a folder with a specific name it seems like I get a hit for folder_name$ but not for folder_name/$. This seems conterintuitive. How can I grep for lines that end with /?

share|improve this question

2 Answers 2

up vote 3 down vote accepted

Yes, the -type d option is used for this.

For example:

$ find /boot -type d
/boot
/boot/grub
/boot/grub/locale
/boot/grub/fonts
/boot/grub/i386-pc

Here's the relevant section of the man page:

   -type c
          File is of type c:

          b      block (buffered) special

          c      character (unbuffered) special

          d      directory

          p      named pipe (FIFO)

          f      regular file

          l      symbolic link; this is never true if the -L option or the
                 -follow option is in effect, unless the symbolic link  is
                 broken.  If you want to search for symbolic links when -L
                 is in effect, use -xtype.

          s      socket

          D      door (Solaris)
share|improve this answer
    
thanks! I looked at the manpage, but I still find them a bit bewildering, must have missed it. :) –  Tor Thommesen Aug 24 '13 at 15:28

As an addition to Zero Piraeus' answer, if you want to include symlinks that resolve to directories:

  • with GNU find:

    find . -xtype d
    
  • POSIXly:

    find . -exec test -d {} \; -print
    

    which you can optimise to

    find . \( -type d -o -type l -exec test -d {} \; \) -print
    

If you want to follow symlinks when descending the directory tree, you'd do:

find -L . -type d

which would report directories and symlinks to directories. If you don't want the symlinks:

  • with GNU find:

    find -L . -xtype d
    
  • POSIXly:

    find -L . -type d ! -exec test -L {} \; -print
    

With zsh:

printf '%s\n' **/*(D/)   # directories
printf '%s\n' **/*(D-/)  # directories, or symlinks to directories
printf '%s\n' ***/*(D/)  # directories, traversing symlinks
printf '%s\n' ***/*(D-/) # directories or symlinks to directories,
                         # traversing symlinks
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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