1

I'm trying to get the number of files in a directory tree.

The command find . -type f lists the files each on new line when I run it but if I store the result of the command in a variable, it stores it all on one line when I then echo that variable. So if I then want to count the number of files via a for cycle, I stumble across a problem with files that have blank spaces in their name.

So is there a way to store the output of the find command in a variable where each file name is on new line? That way by counting the number of lines, I will get the number of files.

Daeto
  • 440
  • 1
  • 6
  • 19
  • Sounds like you just need to put double quotes around the variable when you use it. – Tom Fenech Mar 11 '16 at 15:36
  • 3
    Why not directly use something like `find . -type f | wc -l` to get the number of files? – Julien Lopez Mar 11 '16 at 15:38
  • 1
    Oh you're right, that will be the best way! I already used this command but completely forgot about it, thanks a lot! : ) – Daeto Mar 11 '16 at 15:40
  • @Daeto The accepted answer is a better solution, but the direct one is described here: [I just assigned a variable, but echo $variable shows something else](http://stackoverflow.com/questions/29378566/i-just-assigned-a-variable-but-echo-variable-shows-something-else) – that other guy Mar 11 '16 at 18:25

1 Answers1

2

You can use the wc with -l option to count line in a file. For you case :

find . -type f | wc -l 

should work.

Pierre
  • 1,162
  • 12
  • 29
  • Doesn't work with files with newlines in the name. Also requires running `find` twice if you want to do anything with the found files (which then introduces a race condition where files may be added or removed between the calls to `find`). But without knowing what the OPs **actual** goal here is improving this answer can only be taken so far. – Etan Reisner Mar 11 '16 at 16:39
  • "with newlines in the name", does it really exist ? :) – Pierre Mar 14 '16 at 09:53
  • Often? No. Occasionally? Yes. Better to prepare for it then to be bitten by it? Also yes. – Etan Reisner Mar 14 '16 at 17:57