Page 1 of 1

Get latest file name from directory

Posted: Saturday 11 February 2017 23:31
by Frank84
I needed to get the latest modified (created) file name from a directory, so that i could change that file to the latest OS.Date.
The difficult part was to get the latest modified file name in a specific path. I've found some topics on the internet to use the io.popen command but those were not working for me.

Finally i've found a solution to read the latest modified file in a specific directory and wanted to share it with you guys.

In general it is executing the command ls -t | head -n1 in the directory called dirname, saving the output to a temp file n, and putting this output in a variable called latest_file and then removing the temp file n. After this the output is printed to the domoticz log.

Code: Select all

dirname = "/media/usb/Domoticz/Doorbell/Videos/"

commandArray = {}
function latest_file_name()
n = os.tmpname ()
		os.execute("ls -t "..dirname.." | head -n1 > " ..n)
		for line in io.lines (n) do
			latest_file = line
		end
	os.remove (n)
end

if (devicechanged['Test'] == 'On')then
	latest_file_name()
	print(latest_file)
end

return commandArray
After the difficult part I created a lua script so it changes a file to the current os.date:

Code: Select all

Date_Time = os.date ("%Y%m%d_%H%M%S")
dirname = "/media/usb/Domoticz/Doorbell/Videos/"

commandArray = {}

function mv_file()
	os.execute("sudo mv "..dirname..latest_file.." "..dirname.."Doorbell_"..Date_Time..".mkv")
end

function latest_file_name()
n = os.tmpname ()
		os.execute("ls -t "..dirname.." | head -n1 > " ..n)
		for line in io.lines (n) do
			latest_file = line
		end
	os.remove (n)
end

if (devicechanged['Test'] == 'On')then
	latest_file_name()
	mv_file()
end

return commandArray