首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >替换powershell中文本文件中http链接中的内容

替换powershell中文本文件中http链接中的内容
EN

Stack Overflow用户
提问于 2018-03-07 17:02:48
回答 1查看 30关注 0票数 1

我是powershell的新手,我创建了以下脚本,它提取http: / /和下一个/之间的内容,转换它,然后替换初始匹配:

代码语言:javascript
复制
$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或其他什么,但不使用硬编码的文本。有人能帮我吗?

我在想:

代码语言:javascript
复制
$path = "myFile";
Get-Content $path | Foreach {$_ -replace "(?<=http://).+?(?=/.*)",".+?(?=/.*).newEnvironment"};
Set-Content $path;  

但它不起作用,即使它以这种方式设置链接:

代码语言:javascript
复制
http://.+?(?=/.*).newEnvironment/asd/test.aspx
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-03-07 17:47:22

看来你想

  • 移除"www."部件
  • $newEnvironment的值附加到任何网址

一种方法就是搜索.

  • 前面是"http://“- (?<=http://)”。
  • 从“www”开始- www\.
  • 具有除空格或斜杠以外的字符,如组1- ([^/ ]+)
  • 为了安全起见,还没有$newEnvironment - (?!\.$newEnvironment)紧随其后。

并将其替换为"regex 1“+”+ $newEnvironment:

代码语言:javascript
复制
$fileName = "myfile"
$newEnvironment = "NewEnvironment"

$pattern = "(?<=http://)www\.([^/ ]+)(?!\.$newEnvironment)"
$replacement = "`$1.$newEnvironment"

(Get-Content $path) -replace $pattern,$replacement | Set-Content $path

Powershell操作符通常对数组很满意。Get-Content将为您提供一个行数组,-replace将处理所有这些行。( -replace的另一个实用特性是您可以将其链接起来:"abc" -replace "a","A" -replace "b","B"将工作。)

这意味着不需要编写手动的foreach循环。唯一需要的是一对括号,这样Get-Content就不会将-replace误认为是一个参数。

$1是组1的反向引用,反勾号是Powershell的转义字符,因为$本身在Powershell和regex中都有意义。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49157477

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档