0

I have a situation where I don't know the complete name of a file but I need to search for it to see if it exists. the part of the file name that I don't know is a sequence number at the end of the name. For example, the file name looks like this:

myfile.1234567890.12.xff

the ".12" part is what I don't know. However, I just need to know if any files starting with "myfile.1234567890" and ending with ".xff" exist.

How would i accomplish this in lua? thanks.

dot
  • 14,928
  • 41
  • 110
  • 218

2 Answers2

2

Version for Windows.
No external libraries.

local function recursive_search(path, OS_filemask, filename_pattern, search_for_dirs, only_top_level)
   path = path:gsub('/', '\\'):gsub('\\*$', '\\', 1)
   OS_filemask = OS_filemask or '*.*'
   filename_pattern = filename_pattern or '.*'
   local arr = {}
   local pipe = io.popen((search_for_dirs and 'dir /b/ad "' or 'dir /b/a-d "')..path..OS_filemask..'" 2> nul')
   for f in pipe:lines() do
      if f:lower():match('^'..filename_pattern..'$') then
         table.insert(arr, path..f)
      end
   end
   pipe:close()
   if not only_top_level then
      for _, path in ipairs(recursive_search(path, nil, nil, true, true)) do
         for _, f in ipairs(recursive_search(path, OS_filemask, filename_pattern, search_for_dirs)) do
            table.insert(arr, f)
         end
      end
   end
   return arr
end

-- Find all number-named JPEG picures in C:\Games
-- OS filemask can't filter it properly, use Lua pattern to restrict search conditions
for _, f in ipairs(recursive_search('C:\\Games', '*.jp*g', '%d+%.jpe?g')) do
   print(f)
end

-- Find all folders in C:\WINDOWS with 32 in its name
-- OS filemask is enough here
for _, f in ipairs(recursive_search('C:\\WINDOWS', '*32*', nil, true)) do
   print(f)
end

-- myfile.1234567890.12.xff
for _, f in ipairs(recursive_search('C:\\', 'myfile.1234567890.*.xff', 'myfile%.1234567890%.%d+%.xff')) do
   print(f)
end
Egor Skriptunoff
  • 23,359
  • 2
  • 34
  • 64
0

You can find an implementation of glob function in Lua at this link. But you could just iterate through the list of all files in the folder and check them against your pattern. You could use LuaFileSystem lfs.dir() to get the list.

Alex P.
  • 30,437
  • 17
  • 118
  • 169