我有 2 個文件,其中 1 個包含某些關鍵字,另一個包含路徑列表。我想從第一個檔案清單中搜尋關鍵字到檔案路徑清單中,如果找到,則將檔案從指定的檔案路徑複製到特定的目標資料夾。
第一個文件內容
Keyword1
Keyword2
Keyword3
Keyword4
第二個文件內容
\\server\path...\Keyword1.txt
\\server\path...\Keyword1_0_1.txt
\\server\path...\Keyword2_0_1.txt
\\server\path...\Keyword2_1_9.txt
\\server\path...\Keyword3_1_0_1.txt
為此我必須編寫 Windows 批次腳本。
================================================== = =========
抱歉@pimp-juice-it,我不知道如何貼上螢幕截圖。因此複製貼上下面的輸出 -
d:\Temp_Script\Script>FOR /R "D:\Temp_Script\Source\33.txt" %G IN (55*) DO ECHO "55" d:\Temp_Script\Script>CALL :FileExist "55" "D: \Temp_Script\Source\44.txt" d:\Temp_Script\Script>FOR /R "D:\Temp_Script\Source\44.txt" %G IN (55*) DO ECHO "55" d:\Temp_Script\Script> CALL :FileExist "55" "D:\Temp_Script\Source\55.txt" d:\Temp_Script\Script>FOR /R "D:\Temp_Script\Source\55.txt" %G IN (55*) DO ECHO " 55" d:\Temp_Script\Script>CALL :FileExist "55" "D:\Temp_Script\Source\55 - 複製(2).txt" d:\Temp_Script\Script>FOR /R "D:\Temp_Script\Source\ 55 - 複製(2).txt" %G IN (55*) DO ECHO "55" d:\Temp_Script\Script>CALL :FileExist "55" "D:\Temp_Script\Source\55 - Copy.txt"
正如您可以看到 UNC 中存在關鍵字“55”,但條件在 FOR 循環中仍然未驗證為 True,並且將直接轉到下一個 UNC。下面是程式碼 -
:FileExist FOR /R "%~2" %%G IN (%~1*) DO ECHO "%~1"
答案1
您可以循環遍歷“關鍵字”列表一次,並使用迭代的關鍵字值以及一些封閉的通配符作為搜尋字串IE *<Keyword>*
。您可以從檔案清單中遍歷每個 UNC 路徑值的目錄樹,並僅對那些與搜尋字串「keywords」相符的目錄樹執行複製作業。
本質上雖然...
批次腳本
@ECHO ON
SET "strList=\\server\Folder\Path\SearchStrings.txt"
SET "pathList=\\server\Folder\Path\UNCPaths.txt"
SET "targetPath=\\server\target\folder\path"
FOR /F "USEBACKQ TOKENS=*" %%S IN ("%strList%") DO CALL :Paths "%%~S"
PAUSE
EXIT
:Paths
FOR /F "USEBACKQ TOKENS=*" %%P IN ("%pathList%") DO CALL :FileExist "%~1" "%%~P"
GOTO :EOF
:FileExist
FOR /R "%~2" %%C IN (*%~1*) DO XCOPY /F /Y "%%~C" "%targetPath%\"
GOTO :EOF
更多資源
-
CALL 指令將會將控制權傳遞給指定標籤以及任何指定參數之後的語句。若要退出子例程,請指定
GOTO:eof
這會將控制權轉移到目前子例程的末端。 -
FOR /R [[drive:]path] %variable IN (set) DO command [command-parameters] Walks the directory tree rooted at [drive:]path, executing the FOR statement in each directory of the tree. If no directory specification is specified after /R then the current directory is assumed. If set is just a single period (.) character then it will just enumerate the directory tree.