#navi(../)
* PowerShellでテキストファイル内の文字列を置換する方法・replace, creplace [#faf9af00]
テキストファイル内に存在する指定した文字列を指定した文字列で置換する方法を以下に記します。

#contents
#htmlinsertpcsp(win-top.html,win-sp.html)

* replaceを使用し置換する [#z87c9645]
replaceを使用すると以下にように-repalceの左側に置換前文字列、右側に置換後の文字列を指定します。~
以下、コマンドラインからの実行結果です。
 PS C:\Users\sakura> "windows" -replace "w", "W"
 WindoWs
w->Wに置換されているのが確認できます。

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

* creplace [#oe4c2f33]
creplaceもreplaceと同様の書式になります。~
ただし、replaceとの違いは大文字小文字を区別します。~
以下、コマンドラインからの実行結果です。
 PS C:\Users\sakura> "win Win WIN" -creplace "win", "Win"
 Win Win WIN

* テキストファイルの文字列を置換する [#x5a3f79c]
以下の書式により置換が可能になります。~
-大文字小文字を区別しない(replace)
 Get-Content ファイル名 | foreach { $_ -replace "置換前文字列", "置換後文字列" }
foreachは%とも記述できます。
 Get-Content ファイル名 | % { $_ -replace "置換前文字列", "置換後文字列" }
-大文字小文字を区別する(creplace)
 Get-Content ファイル名 | foreach { $_ -creplace "置換前文字列", "置換後文字列" }
foreachは%とも記述できます。
 Get-Content ファイル名 | % { $_ -creplace "置換前文字列", "置換後文字列" }

* 実行結果 [#ia074cf9]
実際にテキストファイルを用意して実行してみます。

以下のテキストファイルを用意し実行しました。
#ref(win.txt)
 WiNdOwSVista
 windows7
 WINdows8
 WINDOWS8.1
 winDOWS10

** repalceで実行 [#taed5e97]
 PS C:\Users\sakura> Get-Content .\win.txt | % { $_ -replace "windows", "Windows" }
 WindowsVista
 Windows7
 Windows8
 Windows8.1
 Windows10

** crepalceで実行 [#jc8100f1]
 PS C:\Users\sakura> Get-Content .\win.txt | % { $_ -creplace "windows", "Windows" }
 WiNdOwSVista
 Windows7
 WINdows8
 WINDOWS8.1
 winDOWS10

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

#htmlinsertpcsp(win-btm.html,win-sp.html)

トップ   編集 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS