how to get files count in a directory using ruby
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) }
Chef: Count the number of files in a folder
count
seems to be 0
(Fixnum).
You may wanna try:
file 'C:\Users\Desktop\Chef-file\count.txt' do
dir = 'C:\Users\Desktop\Chef-Commands'
count = Dir[File.join(dir, '**', '*')].count { |file| File.file?(file)}
content count.to_s
end
How to get the total size of files in a Directory in Ruby
In Windows, You can use win32ole gem to calculate the same
require 'win32ole'
fso = WIN32OLE.new('Scripting.FileSystemObject')
folder = fso.GetFolder('directory path')
p folder.name
p folder.size
p folder.path
Get names of all files from a folder with Ruby
You also have the shortcut option of
Dir["/path/to/search/*"]
and if you want to find all Ruby files in any folder or sub-folder:
Dir["/path/to/search/**/*.rb"]
Count the number of lines in a file without reading entire file into memory?
If you are in a Unix environment, you can just let wc -l
do the work.
It will not load the whole file into memory; since it is optimized for streaming file and count word/line the performance is good enough rather then streaming the file yourself in Ruby.
SSCCE:
filename = 'a_file/somewhere.txt'
line_count = `wc -l "#{filename}"`.strip.split(' ')[0].to_i
p line_count
Or if you want a collection of files passed on the command line:
wc_output = `wc -l "#{ARGV.join('" "')}"`
line_count = wc_output.match(/^ *([0-9]+) +total$/).captures[0].to_i
p line_count
How do I get all the files names in one folder using Ruby?
Break the problem into into parts. The method get_first_part
should go something like:
Use Dir to get a listing of files.
Iterate over each file and;
Extract the "name" ('This_is_a_very_good_movie') and the "tag" ('y08iPnx_ktA'). The same regex should be used for each file.
If the "tag" matches what is being looked for, return "name".
Happy coding.
Play around in the REPL and have fun :-)
Get all file names in a directory with ruby
Dir.new('.').each {|file| puts file }
Note that this will include . and ..
Related Topics
Ruby: Insert Spaces Every X Number of Characters
What Are the Reserved Words Begin or End Used for in Ruby
How to Use Define_Method Inside Initialize()
Object.Valid? Returns False But Object.Errors.Full_Messages Is Empty
Rails Belongs_To Association (With :Class_Name) Returns Nil
No Database Connection in Rails Console
What's the Variable Scope Within 'Class_Eval' String
Finding All the Users That Have Duplicate Names
Ruby Regex What Does the \1 Mean for Gsub
"Require File.Dirname(_File_)" -- How to Safely Undo Filesystem Dependency
Add Comment to User and Post Models (Ruby on Rails)