Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively counting files in a Linux directory

Tags:

linux

How can I recursively count files in a Linux directory?

I found this:

find DIR_NAME -type f ¦ wc -l 

But when I run this it returns the following error.

find: paths must precede expression: ¦

like image 931
Robert Buckley Avatar asked Feb 06 '12 07:02

Robert Buckley


People also ask

How do I count files in a folder and subfolders?

Use File Explorer Open the folder and select all the subfolders or files either manually or by pressing CTRL+A shortcut. If you choose manually, you can select and omit particular files. You can now see the total count near the left bottom of the window. Repeat the same for the files inside a folder and subfolder too.

How do I count the number of files in a directory?

To determine how many files there are in the current directory, put in ls -1 | wc -l. This uses wc to do a count of the number of lines (-l) in the output of ls -1.


2 Answers

For the current directory:

find -type f | wc -l 
like image 45
Abhishek Maurya Avatar answered Oct 19 '22 18:10

Abhishek Maurya


This should work:

find DIR_NAME -type f | wc -l 

Explanation:

  • -type f to include only files.
  • | (and not ¦) redirects find command's standard output to wc command's standard input.
  • wc (short for word count) counts newlines, words and bytes on its input (docs).
  • -l to count just newlines.

Notes:

  • Replace DIR_NAME with . to execute the command in the current folder.
  • You can also remove the -type f to include directories (and symlinks) in the count.
  • It's possible this command will overcount if filenames can contain newline characters.

Explanation of why your example does not work:

In the command you showed, you do not use the "Pipe" (|) to kind-of connect two commands, but the broken bar (¦) which the shell does not recognize as a command or something similar. That's why you get that error message.

like image 119
paulsm4 Avatar answered Oct 19 '22 19:10

paulsm4