PowerShellでテキストファイル内の文字列を置換する方法・replace, creplace

テキストファイル内に存在する指定した文字列を指定した文字列で置換する方法を以下に記します。


スポンサーリンク

replaceを使用し置換する

replaceを使用すると以下にように-repalceの左側に置換前文字列、右側に置換後の文字列を指定します。
以下、コマンドラインからの実行結果です。

PS C:\Users\sakura> "windows" -replace "w", "W"
WindoWs

w->Wに置換されているのが確認できます。

尚、replaceは大文字小文字を区別しません。

creplace

creplaceもreplaceと同様の書式になります。
ただし、replaceとの違いは大文字小文字を区別します。
以下、コマンドラインからの実行結果です。

PS C:\Users\sakura> "win Win WIN" -creplace "win", "Win"
Win Win WIN

テキストファイルの文字列を置換する

以下の書式により置換が可能になります。

実行結果

実際にテキストファイルを用意して実行してみます。

以下のテキストファイルを用意し実行しました。

WiNdOwSVista
windows7
WINdows8
WINDOWS8.1
winDOWS10

repalceで実行

PS C:\Users\sakura> Get-Content .\win.txt | % { $_ -replace "windows", "Windows" }
WindowsVista
Windows7
Windows8
Windows8.1
Windows10

crepalceで実行

PS C:\Users\sakura> Get-Content .\win.txt | % { $_ -creplace "windows", "Windows" }
WiNdOwSVista
Windows7
WINdows8
WINDOWS8.1
winDOWS10

以上、replace, creplaceを使用してテキストファイル内の文字列を置換する方法でした。


添付ファイル: filewin.txt 2186件 [詳細]

トップ   編集 凍結 差分 履歴 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2025-03-15 (土) 08:47:09