首页 > 解决方案 > 在 Powershell 脚本中替换文本文件中的某些字符

问题描述

我有一个带有文本示例的文本文件:

+ Starting at line 0 $/A/B/C/Demo\Demo.sln
+ class string foo{ 
+      return "a\b"; 
+ }

我想将 \ 斜杠替换为 / 的路径。但它应该改变代码其他部分的\。为此,我必须使用 Powershell。预期代码:

+ Starting at line 0 $/A/B/C/Demo/Demo.sln
+ class string foo{ 
+      return "a\b"; 
+ }

标签: powershell

解决方案


一种解决方案是在文件中包含至少一个“\”字符的每个字符串上使用Test-Path $string -IsValid函数(此处'.*\\.*'的文档),为此,您可以将文件中的文本拆分为空格并检查哪个结果字符串与正则表达式匹配.

结果可能是这样的:

$text = Get-Content -Path 'C:\...\data.txt'
$text -split '\s' | ForEach-Object {
    #find strings with \ only
    if($_ -match '.*\\.*') {
        #if the string is like a path
        if(Test-Path $_ -IsValid) {
            #replace \ with /
            $replace = $_ -replace '\\','/'
            #replace path string with fixed path (note: [regex]::escape(...) is necessary to avoid using regex in this replace, because $_ contains some characters like \ end similar)
            $text = $text -replace [regex]::escape($_), $replace
        }
    }
}

$text > 'C:\...\result.txt'

推荐阅读