Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listing the files in a directory and all subdirectory

Is there any class in ruby for listing all the files in a directory and all the files in the subdirectory?

like image 585
amir amir Avatar asked Aug 24 '11 20:08

amir amir


People also ask

How do I list files in a directory and subdirectories?

The ls command is used to list files or directories in Linux and other Unix-based operating systems. Just like you navigate in your File explorer or Finder with a GUI, the ls command allows you to list all files or directories in the current directory by default, and further interact with them via the command line.

How do I list files in all subdirectories?

By default, ls lists just one directory. If you name one or more directories on the command line, ls will list each one. The -R (uppercase R) option lists all subdirectories, recursively.

Which command is used to show the directory and all subdirectories of files?

Use the ls command to display the contents of a directory. The ls command writes to standard output the contents of each specified Directory or the name of each specified File, along with any other information you ask for with the flags.

How do I get a list of files in a directory and subfolders in Windows?

Substitute dir /A:D. /B /S > FolderList. txt to produce a list of all folders and all subfolders of the directory.


1 Answers

You might look at Dir.glob. You can pass it the **/* path which will give you everything in the folder and its subdirectories:

records = Dir.glob("path/to/your/root/directory/**/*") # Will return everything - files and folders - from the root level of your root directory and all it's subfolders # => ["file1.txt", "file2.txt", "dir1", "dir1/file1.txt", ...] 

Since you probably want a list of files, excluding folders, you can use:

records = Dir.glob("path/to/your/root/directory/**/*").reject { |f| File.directory?(f) } 
like image 128
Dylan Markow Avatar answered Oct 13 '22 11:10

Dylan Markow