2016-08-13 6 views
0

ここで何か助けを得ることを望んでいた。私は、監視対象とエンディング機能が削除されたファイルの束を持って、次のようにファイルを検索します。特定の文字の後にファイルの名前を変更する

姓、FirstName_DOS-Facility.pdf

私は現在、以下を実行します。

@echo off 

for /F "tokens=1,* delims=-" %%a in ('dir /A-D /B "*.pdf"') do (
    ECHO move "%%a-%%b" "%%a%%~xb" 
) 

そして、それLastName、FirstName_DOS.pdfを作成します。

私が実行している問題は、同じ名前の複数のファイルです。私のバッチファイルは、古いファイルを新しいファイルに置き換えます。必要に応じて_1.pdf _2.pdf _3.pdfなどを追加する方法はありますか?お手伝いありがとう!

答えて

1

タスク要件に適したコメント付きバッチコードです。使用するコマンドを理解し、どのように彼らは、コマンドプロンプトウィンドウを開き、そこに次のコマンドを実行し、完全にページが非常に慎重に、各コマンドのために表示されているすべてのヘルプを読んで、仕事のため

@echo off 
setlocal EnableExtensions EnableDelayedExpansion 

for /F "tokens=1* delims=-" %%a in ('dir "*-*.pdf" /A-D /B 2^>nul') do (
    if not exist "%%a%%~xb" (
     ren "%%a-%%b" "%%a%%~xb" 
    ) else (
     call :GetNextAppendix "%%a" "%%~xb" 
     ren "%%a-%%b" "%%a!NextAppendix!%%~xb" 
    ) 
) 

endlocal 
goto :EOF 

rem This subroutine inserts between file name passed as first argument 
rem and file extension passed as second argument an underscore and an 
rem incrementing number in range 1 to 50000 and checks if a file with 
rem this name already exists. If there is no file with current number 
rem in file name, this number with the preceding underscore is assigned 
rem to an environment variable used in parent process routine to rename 
rem the file. 

:GetNextAppendix 
for /L %%I in (1,1,50000) do (
    if not exist "%~1_%%I%~2" (
     set "NextAppendix=_%%I" 
     goto :EOF 
    ) 
) 

rem Windows command interpreter should never reach this part of the code. 
rem But in case of this really happens, simply clear the appendix variable 
rem which results in a failed renaming of file in parent process loop 
rem above with output of an error message because of file already existing. 

set "NextAppendix=" 
goto :EOF 

  • call /?
  • echo /?
  • endlocal /?
  • for /?
  • goto /?
  • if /?
  • ren /?
  • set /?
  • setlocal /?

そして>コマンドDIRの実行に適用すると、リダイレクト操作として解釈されていない^でエスケープリダイレクト演算子で2>nulある2^>nulの説明についても、Microsoftの記事についてUsing command redirection operatorsを参照してくださいコマンドの場合はコマンドライン内で無効な位置にあります。

これを抑制するために、デバイスNULにSTDERRからワイルドカードパターン*-*.pdfと一致するファイルにDIRによるエラーメッセージの出力をリダイレクトします。

+0

これが完了しました。どうもありがとうございます!!今私はファイル名でDOSを読む方法を見つけることができる場合は、フォルダを作成する(または存在する場合は単にファイルを移動)、そこにファイルを移動すると、私の人生は簡単になります! –

0

test.batにスクリプトを保存し、開いているCmdプロンプトから実行します。 dirの値をパスに置き換えます。エラーがあれば教えてください。

@echo off 
setlocal enabledelayedexpansion 
set "dir=C:\My_Files" 
pushd "%dir%" 
for /F "tokens=1,* delims=-" %%a in ('dir /A-D /B "*.pdf" 2^>nul') do (
    call :rename %%a %%b) 
popd 
exit /b 

:rename 
set "i=" 
:loop 
if exist "%1!i!%~x2" (set /a "i+=1" & goto :loop) 
ren "%1-%2" "%1!i!%~x2" 
exit /b 
+0

Pls Upvote and Answerボックスの左側にあるボタンを使用して、必要に応じた回答を受け入れます。 – sambul35

+0

返信いただきありがとうございます!このスクリプトは、「システムは指定されたファイルを見つけることができません」というエラーを2回だけ与えています。フォルダに2つの.pdfがあります。 –

+0

スクリプトを更新しました。 _dir_パスを自分のパスに置き換えましたか? – sambul35

関連する問題