Powershell - 删除目录中所有文件中的每隔一行

时间:2017-11-09 10:22:21

标签: powershell

我对Powershell来说还是一个新手。我运行了一些编辑过的代码,这些代码应该替换文件中的某些文本,但它没有按预期工作,而是重复文件中的每一行。对于那些需要轻笑的人的代码。

除非它为文件夹中的1000多个文档做了这件事,否则不会这么糟糕,因此,我需要编写一个脚本来撤消造成的损坏。我已经用谷歌搜索了它,可以找到很多做类似事情的事情,但我无法采取任何措施并重新安排我的需求。那么有人可以帮忙吗?

这是我的原始代码:

function ChangeText{
    $obj = Get-ChildItem -recurse -Include *.xml  -path "************"
    foreach($item in $obj)
    {
        (Get-Content $item.PSPath) |
        Foreach-Object { 
            $_ -replace "Unwanted Text", "Wanted Text" 
            $_ -replace "Other Unwanted Text", "Wanted Text" ##This line is the line I stupidly added which caused the issue 
        } |
        Set-Content $item.PSPath
    }
}

ChangeText

示例:我需要转:

Help Me please
Help Me please
I made a mistake with the script
I made a mistake with a script
and I need your help to fix it. 
and I need your help to fix it. 

分为:

Help Me please
I made a mistake with the script
and I need your help to fix it. 

我不能仅仅依靠删除重复的行作为原始行上的原始替换文本,因此某些文件显示重复的行,有些显示1个原始行和1个更改的行。

保留哪一行以及丢弃哪一行并不重要,因为我可以对其运行原始脚本以再次更改文本(不做我的更改)

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:5)

您可以使用模数来消除交替的线条。

$i = 0
Get-Content file.txt | Where-Object { $i % 2 -eq 0; $i++ }
相关问题