How can you find the most recently modified folder in a directory using Ruby?
Dir.glob("a_directory/*/").max_by {|f| File.mtime(f)}
Dir.glob("a_directory/*/")
returns all the directory names in a_directory
(as strings) and max_by
returns the name of the directory for which File.mtime
returns the greatest (i.e. most recent) date.
Edit: updated answer to match the updated question
Ruby: Finding most recently modified file
Dir.glob("*").max_by {|f| File.mtime(f)}
How can I get the path for the last created file in a directory using Ruby?
I think this is fairly brief:
Dir.glob(File.join(path, '*.*')).max { |a,b| File.ctime(a) <=> File.ctime(b) }
How to get last modified file in a directory to pass to system commands using Ruby?
There's no need to shell out to ls
and parse its output at all. Ruby gives you standard library methods to fetch directory contents and examine file mtimes. Here's a ruby method to return the name of a file in a directory with the latest mtime.
def last_modified_in dir
Dir.glob( File.join( dir,'*' ) ).
select {|f| File.file? f }.
sort_by {|f| File.mtime f }.
last
end
irb> system 'mkdir -p /tmp/foo'
irb> system 'rm /tmp/foo/*'
irb> ('a'..'c').each { |f| system "touch /tmp/foo/#{f}"; sleep 1; }
irb> puts last_modified_in '/tmp/foo'
# => /tmp/foo/c
Ruby - Get the second most recent file from a directory?
You can do as below using Ruby 2.2.0, which added an optional argument to the methods Enumerable#max_by
, Enumerable#min_by
and Enumerable#min
etc.
Dir.glob("./logs/*").max_by(2) {|f| File.mtime(f)}
# gives first 2 maximun.
# If you want the second most recent
Dir.glob("./logs/*").max_by(2) {|f| File.mtime(f)}.last
max_by(n) {|obj| block } → obj
If the
n
argument is given, minimum n elements are returned as an array.
How to find most recently modified file in a remote directory (via ssh)?
This is less a Net::SSH question as it is "What command can I issue to find the most recently modified file?"
SSH connections can issue a command, so once you know what command to send, or execute, you're done. I'd look at:
ls -Alt path/to/files | sed -n '2p'
Fleshing out something more usable results in:
require 'net/ssh'
HOST = 'hostname.domain'
USER = 'user'
PASSWORD = "password"
output = Net::SSH.start(HOST, USER, :password => PASSWORD) { |ssh|
ssh.exec!('ls -alt . | grep pattern_to_find')
}
puts output
Which, after filling in the fields with the right values and running it, connected to one of my hosts at work and returned something like:
drwxr-xr-x 11 xxxxxxxxxxxx xxxxxxxxx 4096 Oct 2 16:20 development
If you have multiple hits you need to retrieve, either expand the pattern after grep
or discard the pipe to grep
and parse your resulting output in Ruby once the command returns. You can also discard the t
flag from ls
if you want to sort locally, though it's a better idea to offload as much of the processing to the far-side host, rather than have it return a huge glob of data and process it locally. The less you return, the faster your overall code will be.
How to order files by last modified time in ruby?
How about simply:
# If you want 'modified time', oldest first
files_sorted_by_time = Dir['*'].sort_by{ |f| File.mtime(f) }
# If you want 'directory change time' (creation time for Windows)
files_sorted_by_time = Dir['*'].sort_by{ |f| File.ctime(f) }
Getting a list of folders in a directory
Jordan is close, but Dir.entries
doesn't return the full path that File.directory?
expects. Try this:
Dir.entries('/your_dir').select {|entry| File.directory? File.join('/your_dir',entry) and !(entry =='.' || entry == '..') }
How to search a folder and all of its subfolders for files of a certain type
You want the Find module. Find.find
takes a string containing a path, and will pass the parent path along with the path of each file and sub-directory to an accompanying block. Some example code:
require 'find'
pdf_file_paths = []
Find.find('path/to/search') do |path|
pdf_file_paths << path if path =~ /.*\.pdf$/
end
That will recursively search a path, and store all file names ending in .pdf in an array.
Related Topics
When Is the Do Keyword Required in Ruby
Assign to an Array and Replace Emerged Nil Values
Rails 4 - Heroku SQLite3 Error
Can You Have Multiple Versions of a Gem in a Gemfile
Nokogiri Fails to Install on Os X
Split Float into Integer and Decimals in Ruby
Ruby CSV.Each in While Loop Not Executing Second Time Through
Accessing a Ruby Hash with a Variable as the Key
Ror: Meaning of "User ||= User.New"
Getting Error (Exit Code 2) for Bootsnap, Not Allowing to Set Up Rails Server
What Is an Eoferror in Ruby File I/O
I Trying to Make a Code That Gives the User a Personal Number After They Have Made an User
Why Can't We Override '||' and '&&'
Searching from a Range of Ids in Activerecord
Uploading New Products with Multiple Variant Options
How to Convert an Octal Number to Decimal in Ruby
How to Read a Clients Windows Login Name Using Ruby on Rails