0

我想在 n 个子文件夹中搜索一个文件(在 Windows 环境中)。然后复制该文件并放在目标文件夹中。

4

1 回答 1

2
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")
于 2020-02-27T12:22:27.327 回答