简体   繁体   中英

Search a file inside n number of sub folder using LUA script

I want to Search a file inside n number of sub folder (in windows environment). Then copy that file and place in destination folder.

function search_and_copy(filename, src_folder, dest_folder)
   local pipe = io.popen("reg query HKLM\\SYSTEM\\CurrentControlSet\\Control\\Nls\\CodePage /v ACP 2>nul:")
   local acp = pipe:read("*a"):match"ACP%s+REG_SZ%s+(%d+)"
   pipe:close()

   local function search_recursively(path)
      local src_filespec = path..filename
      local file = io.open(src_filespec)
      if file then
         file:close()
         return src_filespec
      end
      local subfolders = {}
      local pipe = io.popen((acp and 'chcp '..acp..'|' or '')..'dir /b/ad "' ..path..'*.*" 2>nul:')
      for line in pipe:lines() do
         table.insert(subfolders, line)
      end
      pipe:close()
      for _, subfolder_name in ipairs(subfolders) do
         src_filespec = search_recursively(path..subfolder_name.."\\")
         if src_filespec then
            return src_filespec
         end
      end
   end

   local src_filespec = search_recursively(src_folder:gsub("/", "\\"):gsub("\\*$", "\\"))
   if src_filespec then
      os.execute('copy /b "'..src_filespec..'" "'..dest_folder:gsub("/", "\\"):gsub("\\*$", "\\")..filename..'" 1>nul: 2>&1')
   end
end

-- find file.txt somewhere on drive C: and save it as D:\Found\file.txt
search_and_copy("file.txt", "C:\\", "D:\\Found")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM