Suppose I have a file structure:

$ cd /home/Desktop
$ ls -d */
Abc/ Qwe/ Zxc/ Rty/

Now I want to iterate through every directory and see if they have any ".pdf" files. Could some one please tell what is the best way to do this?

5 Answers 5

for dir in Abc/ Qwe/ Zxc/ Rty/; do
  result="$(find "$dir" -maxdepth 1 -type f -name '*.pdf' -printf .)"
  echo "Folder '${dir}' contains ${#result} *.pdf files."

This ignores subdirectories.

  • This works exactly I want it to :D Thanks Hauke :)
    – gkmohit
    Jun 4, 2014 at 17:35
  • That assumes GNU find. Jun 4, 2014 at 20:02

Use find /home/Desktop -type f -name '*.pdf'.

  • This lists all the PDF files without indicating which toplevel directories contain any. That's like giving someone a cow when they ask for a hamburger. Jun 4, 2014 at 22:38
  • Incorrect. This lists all pdf files with directories for each file. So you can easily see which file belongs to which directory. Yes, it seems author wanted something more like true/false, but i see no way to figure this out from question
    – gena2x
    Jun 5, 2014 at 10:41

Using find is certainly the fastest way to do it. If you want to restrict the directories to look for, you can use:

find <dir1> <dir2> ... -type f -name '*.pdf'

If you want to count the number of files:

find <dir1> <dir2> ... -type f -name '*.pdf' | wc -l


With zsh:

for dir (Abc Qwe Zxc Rty) {
  print -r "Directory '$dir' contains ${#pdf} *.pdf files"

There are several different ways to do this, depending on what you want to do with the information.

  • If you want a list of directories which directly contain .pdf files (i.e. only at the top level, not within subdirectories), I'd go with this:

    dirname */*.pdf | sort | uniq
  • If you want a list of directories which contain .pdf files at any level (so they could be within subdirectories of the directory), try

    find . -name '*.pdf' | cut -d/ -f2 | sort | uniq

    or, if you want to search only certain subdirectories,

    find Abc Qwe Zxc Rty -name '*.pdf' | cut -d/ -f1 | sort | uniq
  • If you want a list of all the .pdf files within the subdirectories, that's just

    find . -name '*.pdf'
  • If you want a count of .pdf files within each directory, to count only files at the top level I'd use

    dirname */*.pdf | sort | uniq -c

    or to include files in subdirectories

    find . -name '*.pdf' | cut -d/ -f2 | sort | uniq -c

    (you can tell the difference is simply adding the -c option to uniq).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .