0

I'm in a situation where I want a Windows batch file to copy a specific file from a folder with known topology, but unknown what the exact folder names are. So a path of the form, Inbox\XXX\YYY\file.txt, where the XXX and YYY folder names could vary arbitrarily. We can assume the subfolders are unique at both levels (no other subfolders in that location). Is there any way to do this?

1 Answers1

1

cmd.exe

Wildcards can only be used in the very last element of a path. This means you can't use two wildcards for different folders of a path. We have to traverse the file system by other means for which in cmd there is where /R for files, for /D /R for folders and and dir /S for both. Unfortunately cmd.exe also doesn't have command substitution and we must use a for loop to access the found path:

for /f "delims=" %f in ('where /R Inbox file.txt') do copy "%f" C:\Target\

To not rely on the uniqueness you and hedge against unexpectedly existing files we can add an exit after the copying has been done in a .bat script:

REM copy-nested-unique.bat

cd Inbox for /f "delims=" %%i in ('dir /b /a-d /s "file.txt"') do ( copy "%%i" C:\Target
cd .. exit /b )

PowerShell

Wildcards in paths are supported just fine:

Copy-Item -Path 'Inbox\*\*\file.txt' C:\Target\

Bash/busybox

Bash also supports wildcards. On Windows it's available e.g. in ~660KB small standalone busybox:

busybox64u.exe bash -c 'cp "Inbox/*/*/file.txt" C:/Target/'
cachius
  • 859