![](https://batch-file.net/wp-content/themes/cocoon-master/images/b-woman.png)
バッチファイルで
・テキストファイル内の文字列を置換
できます!
![](https://batch-file.net/wp-content/themes/cocoon-master/images/b-woman.png)
バッチファイルから
・Power Shellのコマンドレットを実行
することで実現します!
※演算子「-creplace」等により実現します。
コード
ここでは例として
・デスクトップ配下のテキストファイル「sample.txt」内の
・文字列「(株)」を「株式会社」へ置換
します。
![テキストファイル「sample.txt」](https://batch-file.net/wp-content/uploads/2022/09/bat_textfile_replace_001.png)
![テキストファイル「sample.txt」の内容](https://batch-file.net/wp-content/uploads/2022/09/bat_textfile_replace_002.png)
@echo off
rem 対象ファイル
set targetFile=C:\Users\user\Desktop\sample.txt
rem 置換前文字列
set beforeStr=\(株\)
rem 置換後文字列
set afterStr=株式会社
rem PowerShellのコマンドレットを組み立て
set psCommand="(Get-Content %targetFile%) -creplace '%beforeStr%','%afterStr%' | Out-File -Encoding default %targetFile%"
rem PowerShellのコマンドレットを実行
powershell -NoProfile -ExecutionPolicy Unrestricted %psCommand%
rem 実行結果を確認
if %errorlevel% == 0 (
echo 正常終了しました。戻り値:%errorlevel%
) else (
echo 異常終了しました。戻り値:%errorlevel%
)
echo.
pause
exit
実行結果
テキストファイル内の文字列を置換できました。
※文字列「(株)」を「株式会社」へ置換できました。
![実行結果①](https://batch-file.net/wp-content/uploads/2022/09/bat_textfile_replace_003.png)
![](https://batch-file.net/wp-content/uploads/2022/09/bat_textfile_replace_004.png)
参考①
上記のコードは以下の記事を参考にして作成しました。
参考②
上記で使用した以下の詳細は、公式サイトをご確認ください。
●Power Shellのコマンドレット「Get-Content」
●Power Shellの演算子「-creplace」
●Power Shellのコマンドレット「Out-File」