Batch

從命令提示符儲存一個“!”來自變數中的文件名

  • June 10, 2015

我在一個文件夾中有一組文件,其名稱如test! - 01.avi. 我想為每個具有相同名稱的文件創建一個新文件夾,然後將文件移動到該文件夾中。除瞭如何拉入“!”之外,我什麼都有。並將文件複製到文件夾中。

@ECHO OFF
setlocal enabledelayedexpansion
set "sourcedir=Z:\test"
set folder=null
set file=null
PUSHD %sourcedir%
FOR /f "tokens=* delims=?" %%a in ( 'dir /b /a-d "*[720p].*"'
) DO (
 SET file=%%a
 FOR /f "tokens=1,2,* delims=]-" %%b in ("%%a" "[*] * - * [720p].*"
  ) DO (
  FOR /f "tokens=* delims= " %%e in ("%%c"
   ) DO (
    SET folder=%%e
    FOR /l %%f in (1,1,31) do if "!folder:~-1!"==" " set folder=!folder:~0,-1!
    MD "!folder!"
    MOVE "!file!" .\"!folder!"\ 
    )  
   )   
)
POPD
GOTO :EOF

謝謝參觀

更好地處理文件名保持禁用延遲擴展。(處理子程序中程式碼塊內分配的變數)如下:

@ECHO OFF
SETLOCAL EnableExtensions DisableDelayedExpansion

set "sourcedir=D:\bat\Unusual Names"
PUSHD %sourcedir%

dir /b /a-d "*!a*.*"

FOR /f "tokens=* delims=?" %%a in ( 'dir /b /a-d "*!a*.*"') DO (

 SET "file=%%~nxa"

 rem observe instructions "make a new folder for each file with the same name"
 rem suppose that without extension
 SET "folder=%%~dpna"

 call :DoDelayedExpansion
)
POPD

ENDLOCAL
goto :eof

:DoDelayedExpansion
 echo(
 echo MD "%folder%\" 2>NUL
 echo MOVE "%file%" "%folder%\" 
goto :eof

下一個腳本僅使用我現有的測試數據集給出了一個範例。筆記:

  • 在批處理腳本中使用set "variable=value"帶雙引號的語法來轉義一些具有特殊含義的字元,例如|&<>,並確保沒有(意外忘記)尾隨空格;
  • 和命令僅MD用於調試目的;在調試之前刪除所有內容。MOVE``echo``echo

輸出

==>D:\bat\SF\694616.bat
01exclam!ation.txt
02exc!lam!ation.txt

MD "D:\bat\Unusual Names\01exclam!ation\"
MOVE "01exclam!ation.txt" "D:\bat\Unusual Names\01exclam!ation\"

MD "D:\bat\Unusual Names\02exc!lam!ation\"
MOVE "02exc!lam!ation.txt" "D:\bat\Unusual Names\02exc!lam!ation\"

==>

資源(必讀):

引用自:https://serverfault.com/questions/694616