0

I am trying to copy only latest file from a directory using lua file. Latest file means : depends on modified time/created time. How can i do this?

James Z
  • 12,209
  • 10
  • 24
  • 44
Snehasish
  • 11
  • 3

2 Answers2

2

Referring to this question: How can I get last modified timestamp in Lua

You might be able to leverage the io.popen function to execute a shell command to get the name of the file. It seems like there's no builtin function that exposes filesystem metadata or stats. Something like this might work:

local name_handle = io.popen("ls -t1 | head -n 1")
local filename = name_handle:read()

I'm not familiar with Lua, but perhaps this helps. I imagine that once you have the name of the newest file you can use the other IO functions to do the copying.

Sean Aitken
  • 1,177
  • 1
  • 11
  • 23
  • I am trying to get my result in windows environment. And Output is coming current time always. Not able to fetch latest file time. – Snehasish Feb 07 '20 at 12:23
1
local function get_last_file_name(directory)
   local command = 'dir /a-d /o-d /tw /b "'..directory..'" 2>nul:'
   -- /tw for last modified file
   -- /tc for last created file
   local pipe = io.popen(command)
   local file_name = pipe:read()
   pipe:close()
   return file_name
end

local directory = [[C:\path\to\your\directory\]]
local file_name = get_last_file_name(directory)
if file_name then
   print(file_name)
   -- read the last file
   local file = io.open(directory..file_name)
   local content = file:read"*a"
   file:close()
   -- print content of the last file
   print(content)
else
   print"Directory is empty"
end
Egor Skriptunoff
  • 23,359
  • 2
  • 34
  • 64