PowerShell:
テキストの検索と置換
How to: (方法:)
PowerShell では Get-Content と ForEach-Object, Replace メソッドを使ってテキストを探し、置き換えができます。簡単な例を見てみましょう。
# ファイルからテキストを読み込む
$content = Get-Content 'example.txt'
# 'oldtext' を 'newtext' に置き換える
$content = $content -replace 'oldtext', 'newtext'
# 結果をファイルに出力する
$content | Set-Content 'example.txt'置き換えた後のファイル内容を出力してみます:
Get-Content 'example.txt'これが出力です:
newtext and some other text.Deep Dive (深掘り:)
歴史的に、テキストの検索置き換えは編集作業を自動化するために使われてきました。sedやawkのようなユニックスツールも同様のタスクに使いますが、PowerShellはWindows環境における豊かな機能性とスクリプトの統合性を提供しています。
PowerShell では -replace 演算子の他に .Replace() メソッドや Select-String コマンドレットを使う方法もあります。-replace は正規表現をサポートし、.Replace() は単純な文字列置換にとどまります。