2017-01-18 2 views
0
@echo off 
setlocal enabledelayedexpansion 
for %%j in ("*") do (
    set filename=%%~nj 
    set filename="!filename:(1)=!" 
    if not "!filename!" == "%%~xj" ren "%%j" "!filename!%%~xj" 
) 

ファイルに!filenameが含まれていると、スクリプトで問題が発生します。このエラーを回避するために、!filename!を置き換えることはできますか?感嘆符で問題なくループ内のファイル名を変更する方法はありますか?

+0

あなたは[JREN.BATをチェックアウトする必要があります](http://www.dostips.com/forum/viewtopic.php?t=6081) - 正規表現ファイルの名前を変更するユーティリティ。この解決法は、 'call jren '\(1 \)" "" – dbenham

答えて

0

が無効になったときにfor変数が展開されるように、基本的には、遅れて展開を切り替える必要がある - このように:そのほかに

@echo off 
setlocal DisableDelayedExpansion 
for %%j in ("*") do (
    set "file=%%~j" 
    set "filename=%%~nj" 
    set "fileext=%%~xj" 
    setlocal EnableDelayedExpansion 
    set "filename=!filename:(1)=!" 
    if not "!filename!"=="!fileext!" (
     ren "!file!" "!filename!!fileext!" 
    ) 
    endlocal 
) 

、私は二重引用符を修正しました。私はあなたのスクリプトのロジックをさらにチェックしなかったことに注意してください。

0

遅延拡張を維持するを実行してください。さらに、以下の.batスクリプトは、ターゲット・ファイルがすでに(それ以外の場合は、エラーA duplicate file name exists, or the file cannot be foundが発生します)が存在する場合

  • rename commandが失敗し、そして
  • が現在.bat/.cmdスクリプトがすることはできません実行しているという事実を尊重コメント名前を変更/削除しました。

valid in file names場合、スクリプトは正しく^キャレット、%%記号などのように、すべてのcmd/.batspecial charactersを扱う:

@ECHO OFF 
SETLOCAL EnableExtensions DisableDelayedExpansion 

set "filemask=*"     original file mask 

    rem prepare background for debugging and demonstration 
pushd "D:\bat\Unusual Names" 
set "filemask=0*!*.txt"   narrowed file mask 

for %%j in ("%filemask%") do (
    if /I "%%~fj"=="%~f0" (
     rem do not rename currently running script "%~f0" 
     rem applicable if %filemask% does not exclude %~x0 extension i.e. .bat/.cmd 
     rem  e.g. if "%filemask%"=="*" 
    ) else (
     set "file=%%~j"   name and extension 
     set "filename=%%~nj"  name    only 
     set "fileext=%%~xj"    extension only 
     call :renFile 
    ) 
) 
popd 
ENDLOCAL 
goto :eof 

:renFile 
set "filename=%filename:(1)=%" 
if not "%filename%%fileext%"=="%file%" (
    if exist "%filename%%fileext%" (
      rem renaming is not possible as target file already exists 
     echo ??? "%file%" 
    ) else (
      rem rename command is ECHOed merely for debugging and demonstration 
      rem make it operational no sooner than debugged 
     ECHO ren "%file%" "%filename%%fileext%" 
    ) 
) else (
     rem output for debugging and demonstration 
    echo NER "%filename%%fileext%" 
) 
goto :eof 

サンプル出力

==> dir /B "D:\bat\Unusual Names\0*!*.txt" 
01exclam!ation(1).txt 
02exc!lam!ation.txt 
03exclam!ation!OS!(1).txt 
04exc!lam!ation!OS!%OS%(1).txt 
04exc!lam!ation!OS!%OS%.txt 

==> D:\bat\SO\41714127.bat 
ren "01exclam!ation(1).txt" "01exclam!ation.txt" 
NER "02exc!lam!ation.txt" 
ren "03exclam!ation!OS!(1).txt" "03exclam!ation!OS!.txt" 
??? "04exc!lam!ation!OS!%OS%(1).txt" 
NER "04exc!lam!ation!OS!%OS%.txt" 

==> 
関連する問題