本文介绍了powershell 替换特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 powershell 很陌生,但我正在尝试替换 .xml 文件中的某些字符.看起来我已经在第一步绊倒了.

I am farely new to powershell but I am trying to replace certain characters within .xml files. Looks like I stumble with the first steps already.

例如我会尝试替换:

<?xml version="1.0"?>

<?xml version="2.0"?>

您会在下面找到我到目前为止编写的代码:

Below you'll find the code I wrote so far:

Get-Childitem "C:\Users\jp\Desktop\Test" | ForEach-Object {

        $Content = Get-Content $_.fullname
        $Content = ForEach-Object { $Content -replace "(<?xml version=`"1.0`"?>)","(<?xml version=`"2.0`"?>)" }

        Set-Content $_.fullname $Content -Force

        }

问题是这只是我必须替换的字符串的开始.有没有办法独立于内部字符替换一定范围内的任何文本?

The problem is that this is just the start of the strings I have to replace. Is there a way to replace any text within a certain range independent from the characters inside?

无论我有什么特殊字符,我想知道如何替换完整的字符串.提前致谢.

I wonder how to replace a complete string no matter what special characters I have inside.Thanks in advance.

推荐答案

使用 Escape 方法在运行时转义特殊字符.您不需要转义替换模式:

Use the Escape method to escape special characters at run time. You don't need to escape the replace pattern:

(Get-Content c:\dump\xml) |
ForEach-Object {$_ -replace [regex]::Escape('<?xml version="1.0"?>'),'<?xml version="2.0"?>'} |
Set-Content c:\dump\xml

这篇关于powershell 替换特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 06:00