我是powershell的新手,我创建了以下脚本,它提取http: / /和下一个/之间的内容,转换它,然后替换初始匹配:
$fileName = "myfile"
$newEnvironment = "NewEnvironment"
$config = Get-Content $fileName
$newConfig = $config | % { $_ -replace "http://www.site.de", "http://site.de.$newEnvironment" }
$newConfig = $newConfig | % { $_ -replace "http://www.site.com.tr", "http://site.com.tr.$newEnvironment" }
$newConfig = $newConfig | % { $_ -replace "http://www.site.fr", "http://site.fr.$newEnvironment" }
$newConfig = $newConfig | % { $_ -replace "http://www.site.pl", "http://site.pl.$newEnvironment" }
$newConfig = $newConfig | % { $_ -replace "http://www.site-1.be", "http://site-1.be.$newEnvironment" }
$newConfig = $newConfig | % { $_ -replace "http://www.site-1.nl", "http://site-1.nl.$newEnvironment" }
$newConfig = $newConfig | % { $_ -replace "http://www.site.it", "http://site.it.$newEnvironment" }
$newConfig | Set-Content $fileName 我试图使它更好,也许使用regex或其他什么,但不使用硬编码的文本。有人能帮我吗?
我在想:
$path = "myFile";
Get-Content $path | Foreach {$_ -replace "(?<=http://).+?(?=/.*)",".+?(?=/.*).newEnvironment"};
Set-Content $path; 但它不起作用,即使它以这种方式设置链接:
http://.+?(?=/.*).newEnvironment/asd/test.aspx发布于 2018-03-07 17:47:22
看来你想
"www."部件$newEnvironment的值附加到任何网址一种方法就是搜索.
(?<=http://)”。www\.([^/ ]+)。(?!\.$newEnvironment)紧随其后。并将其替换为"regex 1“+”+ $newEnvironment:
$fileName = "myfile"
$newEnvironment = "NewEnvironment"
$pattern = "(?<=http://)www\.([^/ ]+)(?!\.$newEnvironment)"
$replacement = "`$1.$newEnvironment"
(Get-Content $path) -replace $pattern,$replacement | Set-Content $pathPowershell操作符通常对数组很满意。Get-Content将为您提供一个行数组,-replace将处理所有这些行。( -replace的另一个实用特性是您可以将其链接起来:"abc" -replace "a","A" -replace "b","B"将工作。)
这意味着不需要编写手动的foreach循环。唯一需要的是一对括号,这样Get-Content就不会将-replace误认为是一个参数。
$1是组1的反向引用,反勾号是Powershell的转义字符,因为$本身在Powershell和regex中都有意义。
https://stackoverflow.com/questions/49157477
复制相似问题