Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get files count in a directory using ruby

using ruby how to get number of files in a given Directory,the file count should include count from recursive directories.

Eg: folder1(2 files) -----> folder2(4 files) and folder2 is inside folder1. total count for above case should be 6 files.

is there any function in ruby which fetch me this count.

like image 486
Lohith MV Avatar asked Jul 21 '11 08:07

Lohith MV


People also ask

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

using ruby how to get number of files in a given Directory,the file count should include count from recursive directories. Eg: folder1(2 files) -----> folder2(4 files) and folder2 is inside folder1. total count for above case should be 6 files.

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.

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 files in CMD?

How to count the files in a folder, using Command Prompt (cmd) You can also use the Command Prompt. To count the folders and files in a folder, open the Command Prompt and run the following command: dir /a:-d /s /b "Folder Path" | find /c ":".


2 Answers

The fastest way should be (not including directories in count):

Dir.glob(File.join(your_directory_as_variable_or_string, '**', '*')).select { |file| File.file?(file) }.count 

And shorter:

dir = '~/Documents' Dir[File.join(dir, '**', '*')].count { |file| File.file?(file) } 
like image 56
Mario Uher Avatar answered Oct 02 '22 03:10

Mario Uher


All you need is this, run in the current directory.

Dir["**/*"].length 

It counts directories as files.

like image 22
Ray Toal Avatar answered Oct 02 '22 03:10

Ray Toal