PowerShell的正则表达式组替换(Powershell regex group replaci

2019-06-26 17:42发布

我想,以取代在文件夹中的每个脚本文件一些文本,我想用这个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 }

但我不知道如何保持表达的前半部分,只需更换第二个。 任何想法,我该怎么办呢? 谢谢。

Answer 1:

不知道的表名提供的正则表达式是正确的,但无论如何你可以用捕获的变量替换$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" } | 


文章来源: Powershell regex group replacing