19

フォルダ内のすべてのスクリプトファイルのテキストを置き換えたいのですが、次のPSコードを使用しようとしています。

$pattern = '(FROM [a-zA-Z0-9_.]{1,100})(?<replacement_place>[a-zA-Z0-9_.]{1,7})'
Get-ChildItem -Path 'D:\Scripts' -Recurse -Include *.sql | ForEach-Object { (Get-Content $_.fullname) -replace $pattern, 'replace text' | Set-Content $_.fullname }

しかし、表現の最初の部分を保持し、2番目の部分を置き換える方法がわかりません。どうすればこれを行うことができますか?ありがとう。

4

1 に答える 1

37

テーブル名に提供された正規表現が正しいかどうかはわかりませんが、とにかく、変数$1などを使用し、構文$2に従ってキャプチャに置き換えることができます。'Doe, John' -ireplace '(\w+), (\w+)', '$2 $1'

置換パターンは一重引用符で囲む必要があるか('')、または$置換グループ指定子の符号をエスケープする必要があることに注意してください("`$2 `$1")。

# may better replace with     $pattern = '(FROM) (?<replacement_place>[a-zA-Z0-9_.]{1,7})'
$pattern = '(FROM [a-zA-Z0-9_.]{1,100})(?<replacement_place>[a-zA-Z0-9_.]{1,7})'

Get-ChildItem -Path 'D:\Scripts' -Recurse -Include *.sql | % `
{
   (Get-Content $_.fullname) | % `
     { $_-replace $pattern, '$1 replace text' } | 
     Set-Content $_.fullname -Force
}

置換式で他の変数を参照する必要がある場合は(可能性があります)、二重引用符を使用して、バッククォートでキャプチャドルをエスケープできます。

     { $_-replace $pattern, "`$1 replacement text with $somePoshVariable" } | 
于 2012-08-03T11:29:49.957 に答える