構成ファイルをカスタマイズするためのスクリプトを作成しています。このファイル内の文字列の複数のインスタンスを置き換えたいので、PowerShell を使用してこの作業を実行しようとしました。
単一の置換では問題なく動作しますが、複数の置換を実行すると、そのたびにファイル全体を再度解析する必要があり、ファイルが非常に大きいため、非常に遅くなります。スクリプトは次のようになります。
$original_file = 'path\filename.abc'
$destination_file = 'path\filename.abc.new'
(Get-Content $original_file) | Foreach-Object {
$_ -replace 'something1', 'something1new'
} | Set-Content $destination_file
次のようなものが欲しいのですが、どのように書けばよいか分かりません。
$original_file = 'path\filename.abc'
$destination_file = 'path\filename.abc.new'
(Get-Content $original_file) | Foreach-Object {
$_ -replace 'something1', 'something1aa'
$_ -replace 'something2', 'something2bb'
$_ -replace 'something3', 'something3cc'
$_ -replace 'something4', 'something4dd'
$_ -replace 'something5', 'something5dsf'
$_ -replace 'something6', 'something6dfsfds'
} | Set-Content $destination_file
ベストアンサー1
1 つのオプションは、-replace
操作を連結することです。`
各行の末尾の は改行をエスケープし、PowerShell が次の行の式の解析を続行するようにします。
$original_file = 'path\filename.abc'
$destination_file = 'path\filename.abc.new'
(Get-Content $original_file) | Foreach-Object {
$_ -replace 'something1', 'something1aa' `
-replace 'something2', 'something2bb' `
-replace 'something3', 'something3cc' `
-replace 'something4', 'something4dd' `
-replace 'something5', 'something5dsf' `
-replace 'something6', 'something6dfsfds'
} | Set-Content $destination_file
別のオプションとしては、中間変数を割り当てることです。
$x = $_ -replace 'something1', 'something1aa'
$x = $x -replace 'something2', 'something2bb'
...
$x