Batch For Loop - removing file from folder names

瘦欲@ 提交于 2019-12-11 05:34:06

问题


I have a text file which contains things like:

"C:\Folder A\Test.txt"

I need to copy certain files and their respective containers to a new directory from a directory, but only those files I specify and their parent folder structures.

In my batch:

for /f "delims=" %%a in (C:\audit\test.txt) do (
  robocopy "%%~dpa" "Z:\" "%%~nxa" /E /COPY:DAT /PURGE /MIR /R:1000000 /W:30
)
pause

However, it fails the robocopy, probably to do with the trailing backslash. The Source gets mixed up and shows both the folder and the Z:. This means t he file name from %%~nxa is then part of the destination rather than the file to copy. Any ideas?


回答1:


The backslash is treated as an escape character in this case because it immediately precedes the closing ". If you append a . to the path, the result will be the same path but the backslash will no longer precede the closing " and therefore will not be treated as an escape character for the ending quote.

In the example you've posted both the source and target paths end with a \. Therefore you'll need to add a . to both:

for /f "delims=" %%a in (C:\audit\test.txt) do (
  robocopy "%%~dpa." "Z:\." "%%~nxa" /E /COPY:DAT /PURGE /MIR /R:1000000 /W:30
)
pause



回答2:


/MIR will copy the directory structure recursively, even directories that do not conatin files names in test.txt. Please do not use double quotes for first parameter. /R:1000000 /W:30 /COPY:DAT are default values, so no need to set tehm explicitely.

Please try the folowing code:

for /f "tokens=* delims=" %%a in (C:\audit\test.txt) do (
  robocopy %%~dpa "Z:\" "%%~nxa" /E /PURGE /MIR 
)
pause

If you're using spaces and/or special symbols in file paths, you can try the code below taht uses copy comand:

@echo off
for /f "tokens=* delims=" %%a in (C:\audit\test.txt) do (
    if not exist "Z:\%%~pa" mkdir "Z:\%%~pa"
    copy /Y "%%~a" "Z:\%%~pnxa"
)


来源:https://stackoverflow.com/questions/21388400/batch-for-loop-removing-file-from-folder-names

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!