首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Powershell替换文件中的文本?

如何使用Powershell替换文件中的文本?
EN

Stack Overflow用户
提问于 2019-10-09 01:20:09
回答 2查看 2.6K关注 0票数 0

我想删除.csproj文件中的下列文本

代码语言:javascript
复制
    <EmbeddedResource Include="Properties\licenses.licx" />. 

换句话说,用‘’代替。我试过以下几种方法

代码语言:javascript
复制
$c = (($_ | Get-Content)) | Out-String
if ($c.Contains("<EmbeddedResource Include=""Properties\licenses.licx"" />"))
{
  $c = $c -replace "<EmbeddedResource Include=""Properties\licenses.licx"" />",""

它说正则表达式模式无效。我如何在这里设置正则表达式?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-10-09 02:29:11

您所缺少的只是一个\来转义\文件路径分隔符。还可以添加\r\n以避免项目文件中出现空行。

代码语言:javascript
复制
# $content = Get-Content "File.csproj"

$content = "
<EmbeddedResource Include=`"SomeFile.txt`" />
<EmbeddedResource Include=`"Properties\licenses.licx`" />
<EmbeddedResource Include=`"SomeOtherFile.txt`" />
"

$content = $content -replace '<EmbeddedResource Include="Properties\\licenses.licx" />\r\n',''

# $content | Out-File "File.csproj"

Write-Host $content

# Output
# <EmbeddedResource Include="SomeFile.txt" />
# <EmbeddedResource Include="SomeOtherFile.txt" />
票数 0
EN

Stack Overflow用户

发布于 2019-10-09 02:13:13

您可以执行以下操作:

代码语言:javascript
复制
$content = Get-Content $File
$replace = [regex]::Escape('<EmbeddedResource Include="Properties\licenses.licx" />')
$content = $content -replace $replace

使用[regex]::Escape()将自动为您创建一个转义regex字符串。由于要用空字符串替换匹配,所以只需执行一个简单的string -replace value语法,并放弃替换字符串。只有匹配的字符串将被替换。不匹配的字符串将保持不变。如果在regex字符串(或任何字符串)周围使用单引号,则内部的所有内容都将被视为一个文字字符串,从而使捕获内部引号变得更简单。

另外,您在技术上不需要首先将Get-Content设置为变量。整个命令可以是-replace的LHS命令。

代码语言:javascript
复制
$content = (Get-Content $File) -replace $replace
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58295856

复制
相关文章

相似问题

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