バッチファイルでテキストファイル内の文字列置換
Windowsのバッチファイルでテキストファイル内の特定の文字列を置換する方法について。
入力ファイル「input.txt」内に存在する文字列「foo」を全て「bar」に置換して、出力ファイル「output.txt」に出力する。
出力ファイル「output.txt」が既に存在する場合は、上書き保存される。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | @echo off rem カレントディレクトリ移動(バッチ実行ディレクトリ) cd /d %~dp0 rem 入力ファイル set infilenm=input.txt rem 出力ファイル set outfilenm=output.txt rem 置換前文字列 set beforestr=foo rem 置換後文字列 set afterstr=bar rem 出力ファイル作成 type nul >%outfilenm% rem ファイル編集 setlocal enabledelayedexpansion for /f "delims=" %%A in (%infilenm%) do ( set line=%%A echo !line:%beforestr%=%afterstr%!>>%outfilenm% ) endlocal |
この方法には次の制限がある。
- 入力ファイルの空行は出力されない(for /f は空行を読み飛ばすため)。
- 行頭が「;」の行はコメントとみなされ、出力されない。
- 「!」を含む行は、遅延環境変数の展開により正しく出力されない場合がある。
空行を含むファイルを正確に処理したい場合は、PowerShell の利用を検討する。PowerShell では次のように書ける。
1 | (Get-Content input.txt) -replace 'foo', 'bar' | Set-Content output.txt |
なお、日本語を含むファイルを PowerShell 5.1 で扱う場合は、Set-Content に -Encoding Default を指定する(既定のエンコーディングでは文字化けするため)。
PowerShell版の記事はこちら。
上書きされたら全部消えますけど