I want to Search a file inside n number of sub folder (in windows environment). Then copy that file and place in destination folder.
Asked
Active
Viewed 766 times
0
-
I'm not 100% sure what you mean by "search a file inside n number of sub folder". I'm guessing you are recursively looking for files in sub-directories with a max recursion depth of `n`? I don't know lua, but if you can list the files in one directory (like with this answer: https://stackoverflow.com/a/5303802/1115876) then it should just be a simple matter of something like: ``` def search(dir, max_depth): if max_depth == 0: return for file in dir: if file is file: # do something if file is directory: search(file, max_depth - 1) ``` – QuinnFreedman Feb 27 '20 at 07:18
-
Are folders listed in array `{"C:\\Folder1", "D:\\Folder2"}` or you're searching in subfolders of a single folder? – Egor Skriptunoff Feb 27 '20 at 09:05
-
@EgorSkriptunoff No.. It is not listed in array.. And i want to do it in lua script – Snehasish Feb 27 '20 at 09:23
-
@Snehasish - Do you need to recursively search in subfolders? – Egor Skriptunoff Feb 27 '20 at 09:39
-
@EgorSkriptunoff Yes – Snehasish Feb 27 '20 at 09:52
1 Answers
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")

Egor Skriptunoff
- 23,359
- 2
- 34
- 64