0

I am trying to count how many files and folders I have recursively under a directory with 500K files with find (note: recursively and under). I am using the following command:

find my_folder -name '*' -print | wc -l

But I noticed something strange when running the first part:

find my_folder -name '*' -print

It always prints the folder name (my_folder in this example) first on the first line. This increases the file count by one in my first command

Why is that? and how can I avoid this and make sure find only prints the contents under my_folder?

3
  • 1. This isn't the parent directory (which would be ..), it's the starting directory (.). 2. It's exactly what you're asking: traversing a directory recursively starts with the directory itself, then its contents, the contents of the subdirectories, etc. If you want to exclude the starting directory, do it explicitly, or subtract 1. Jul 21, 2013 at 21:33
  • Thanks @Gilles. Do you know how I can exclude the starting directory? Jul 21, 2013 at 21:38
  • -mindepth 1 is one way, as already mentioned in two answers. Jul 21, 2013 at 21:39

2 Answers 2

2

If you really just want files, you could use -type f. -mindepth 1 would prevent just directories given on the command line from matching.

1

It matches the target directory because the pattern * matches .. Since you are looking for files, you should add -type f, to only match files.

find my_folder -type f

If you have GNU find, you can also use -mindepth 1 to prevent . from matching.

find my_folder -mindepth 1
6
  • Thanks. I have updated the OP. Sorry if I wasn't clear in my first post Jul 21, 2013 at 17:16
  • @user815423426 The second example still matches the updated question.
    – jordanm
    Jul 21, 2013 at 17:17
  • You are right! I probably read it too quickly (I thought it said maxdepth). Sorry for my confusion. Jul 21, 2013 at 17:18
  • No, . and .. are never included by find unless explicitly passed in the list of files passed to find. Jul 21, 2013 at 18:01
  • Thanks @StephaneChazelas. I am a bit confused with your answer. Are you suggesting that -mindepth 1 is not a proper solution here? How can I avoid having find include . and .., and what explains the behavior I see in my OP then? Jul 21, 2013 at 18:51

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.