Powershell-删除/替换特定标记之前的所有文本



我想知道是否有办法从读取文件中删除特定标记/单词之前的所有文本?

尝试通过替换进行操作,但没有任何内容被替换。

$Content = Get-Content $file -Raw 
$Content.replace("*<Document>","") | Out-File $basePath$newFile -Append 

append在那里查看所有替换后的输出。但它返回完整的文件。也许有一种方法可以删除";文件";从文本中?

解决方案:在冥想了几次之后,我做了我需要的!由于这是一个文件是XML并且有两个根节点的问题:

<apphdr></apphdr>
<document></document>

我想到的解决方案就像天空一样清澈,检查必要的根元素的索引,并将所有从零到索引的元素都删除。

$Content = Get-Content $file -Raw
$endIndex = $Content.IndexOf("<Document>")
$afterRemove = $Content.Remove(0,$endIndex) | Out-File $basePath$newFile -Append

在输出文件中,我只得到带有document标记的XML文档!

解决方案(以防有人在问题中遗漏(:问题是XML文件文件有两个根元素(破坏的XML逻辑(

<apphdr></apphdr>
<document></document>

解决方案是检查必要的根元素的索引,并从零到索引全部删除。

$Content = Get-Content $file -Raw # read as raw text
$endIndex = $Content.IndexOf("<Document>") # find index of the Document tag
$afterRemove = $Content.Remove(0,$endIndex) | Out-File $basePath$newFile -Append # Store value after removal and conveyor to new file 

在输出文件中,我只得到带有document标记的XML文档!

最新更新