cmd 循環遍歷目錄並從檔案名稱中刪除特殊字符

cmd 循環遍歷目錄並從檔案名稱中刪除特殊字符

我正在尋找一個命令列腳本,它可以循環遍歷所需目錄中的所有文件,並用空格替換文件名中的任何特殊字元。我陷入了特殊字元的替換邏輯。想要替換(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789)中沒有的任何內容。

for /r C:\yourdirectorypath %F in (*) do replace(filename, regexp, ' ') 

答案1

.bat一個腳本可能會有所幫助。用::rem行進行評論以便更好地理解。

我不知道regexp支持cmd;因此,特定的字串被解析為逐個字符子程式中的基礎:convrt(如果%提供給解析的字串中存在任何百分號,請注意錯誤結果)。

@ECHO OFF >NUL
@SETLOCAL enableextensions
:: all `echo` lines for debugging purposes only (remove no sooner than debugged)
:::: set "_ALLOWED=abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ.0123456789"
:::: set "_REPLWITH=-"
:: next setting suffice as '%variable:StrToFind=NewStr%' is case insensitive
set "_ALLOWED=ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789-"
:: note a blank space in the above line (with no full stop)
:: note last character of %_ALLOWED% value used to be the replace one as follows
set "_REPLWITH=%_ALLOWED:~-1%"

:: a filename sample (no extension) to be converted 
:: containing some batch-exceptional characters
SET "_sample=AÄaá^ cč^DĎ(1!)&°~!.foo~bar"
call :convrt _ELPAMS _sample

:: next lines show an intentional usage (with no subfolder recursion)  
pushd "D:\bat\Unusual Names"
:: create a particular file of an unusual name: echo _sample "%_sample%">"%_sample%.txt"
for /F "delims=" %%G in ('dir /B "A*.txt"') do (
  echo(
  set "_sample=%%~nG"
  call :convrt _ELPAMS _sample
  call :output "for debugging purposes only"
)
popd

ENDLOCAL
goto :eof

Next :convrt subroutine accepts two parameters (passed by reference):
  %1 (output) variable name
  %2 (input)  variable name
The subroutine will return 
 - any `~` tilde character unchanged "it's not a bug, it's a feature";
 - wrong result for any `%` percent sign present in a file name. 

:convrt
SETLOCAL enableextensions disabledelayedexpansion
set "__auxAll=%~2"
call set "__auxAll=%%%~2%%"
echo sub %~2 "%__auxAll%"
set "__result="
:loop
  if "%__auxAll%"=="" goto :endconvrt
  set "__auxOne=%__auxAll:~0,1%"
  set "__auxAll=%__auxAll:~1%"
  call set "__changed=%%_ALLOWED:%__auxOne%=%%"
  if not "%__changed%"=="%_ALLOWED%" (
    set "__result=%__result%%__auxOne%"
  ) else (
    set "__result=%__result%%_REPLWITH%"
  )
goto :loop

:endconvrt
echo sub %~1 "%__result%"

ENDLOCAL&call set "%~1=%__result%"
goto :eof

:output
  rem echo for _sample "%_sample%"
  echo for _ELPAMS "%_ELPAMS%"
goto :eof

輸出樣本。注意這個%案例(經過深思熟慮的拼湊而成):

==>D:\bat\SU\921338.bat
sub _sample "AÄaá^ cč^DĎ(1!)&°~!.foo~bar"
sub _ELPAMS "A-a-- c--D--1----~--foo~bar"

sub _sample "AÄaá^ cč^DĎ(1!)&°~!.foo~bar"
sub _ELPAMS "A-a-- c--D--1----~--foo~bar"
for _ELPAMS "A-a-- c--D--1----~--foo~bar"

sub _sample "AÄzž^ yýS%OS%Š%%OS%%(%1!)&°~%%G!^%~2.foo~bar"
sub _ELPAMS "A-z-- y-S%OS%-%%OS%%-%1----~%%G--%~2-foo~bar"
for _ELPAMS "A-z-- y-SWindows_NT-%OS%-_ELPAMS----~%G--_sample-foo~bar"

資源(必讀,不完整):

相關內容