2016-10-14 6 views
0

Win 2003サーバーでは、サイズが150,000、ソースファイルのサイズが約4GBです。 XMLファイルのいくつかのパターンを再帰的に置き換える必要があります。Windowsの複数のファイルで複数のパターンを置き換えるオプション

$files = Get-ChildItem "source_folder" -Filter *.xml -Recurse 
Write-Host $files.count "files present in source" 
foreach ($file in $files) { 
     (Get-Content $file.PSPath) | 
      Foreach-Object { $_ -replace "string1", "replacement1" } | Foreach-Object { $_ -replace "string2", "replacement2" } | Set-Content $file.PSPath 
     Write-Host $file.PSPath " modified" 
} 

このコードは完了するまでに1時間以上かかります。これを達成する最良の方法は何でしょうか?どのような時間を短縮するためのオプションは何ですか?これを行うにはPERLを使用する方が良いですか?提案は大きな助けになるでしょう!

答えて

1

あなたはperlのワンライナーを使用することができます - のようなもの:

perl -p -i -e 's/oldstring/newstring/g' `grep -ril --include *.xml oldstring *` 

を使用すると、元のファイルのバックアップを保持したい場合:

perl -p -i'.bak' -e 's/oldstring/newstring/g' `grep -ril --include *.xml oldstring *` 
-1

私は同じを持っていませんがあなたがこれほど多くのパイプを避けるならば、これをテストするためのリソースがあると思われます。

$files = Get-ChildItem "source_folder" -Filter *.xml -Recurse 
Write-Host $files.count "files present in source" 
foreach ($file in $files) { 
    $s = Get-Content $file.PSPath 
    $s = $s -replace "string1", "replacement1") -replace "string2", "replacement2" 
    Set-Content $file.PSPath -Value $s 
    Write-Host $file.PSPath " modified" 
} 

パイプこれは回避すべきオーバーヘッドがあります。私はあなたの場合にどれほどの違いがあるかを聞いて興味があります。

出力ファイルのエンコード方法を制御するために、Set-Contentコマンドに-Encodingの値を追加するとよい場合もあります。

1

まず、.NETクラスを使用する必要があります。 それだけで、あなたに多くの時間を節約できます。また、あなたは本当にv3のバージョンの置換(.replaceメソッド)を使用する必要があります。それはより速いです。

ので、それは次のようになります。

foreach ($file in $files) { 
     $content = [System.IO.File]::ReadAllText($file).Replace("val1","val2") 
    [System.IO.File]::WriteAllText($file, $content) 
     Write-Host $file.PSPath " modified" 
} 
1

は、このようなあなたのコードを変更しよう:

$files = Get-ChildItem "C:\temp" -Filter *.xml -Recurse -File 
    foreach ($file in $files) 
    { 

    (Get-Content $file.FullName) | Foreach-Object { 
     $_ -replace 'something1', 'something1aa' ` 
      -replace 'something2', 'something2bb' ` 
      -replace 'something3', 'something3cc' ` 
      -replace 'something4', 'something4dd' ` 
      -replace 'something5', 'something5dsf' ` 
      -replace 'something6', 'something6dfsfds' 
     } | Set-Content $file.FullName 

     Write-Host $file.FullName " analysed" 
    } 
関連する問題