【问题标题】:Delete lines from multiple textfiles in PowerShell从 PowerShell 中的多个文本文件中删除行
【发布时间】:2016-05-15 15:59:02
【问题描述】:

我正在尝试从多个文本文件中删除具有已定义内容的行。

它在核心中工作,但即使没有进行任何更改,它也会重写每个文件,如果您只是修改大约 3000 个登录脚本中的 50 个,这并不酷。
我什至做了一个if语句,但它似乎不起作用。

好吧,这就是我已经拥有的:

#Here $varFind will be escaped from potential RegEx triggers.
$varFindEscaped = [regex]::Escape($varFind)

#Here the deletion happens.
foreach ($file in Get-ChildItem $varPath*$varEnding) {
    $contentBefore = Get-Content $file
    $contentAfter = Get-Content $file | Where-Object {$_ -notmatch $varFindEscaped}
    if ($contentBefore -ne $contentAfter) {Set-Content $file $contentAfter}
}

变量的含义:
$varPath 是登录脚本所在的路径。
$varEnding 是要修改的文件的文件结尾.
$varFind是触发删除行的字符串。

任何帮助将不胜感激。

问候
Löwä 分

【问题讨论】:

    标签: powershell text-files powershell-2.0


    【解决方案1】:

    无论如何,您都必须阅读该文件,但对您的更改条件进行一些改进可能会有所帮助。

    #Here the deletion happens.
    foreach ($file in Get-ChildItem $varPath*$varEnding) {
        $data = (Get-Content $file)
        If($data -match $varFindEscaped){
            $data | Where-Object {$_ -notmatch $varFindEscaped} | Set-Content $file
        }
    }
    

    将文件读入$data。检查文件中是否存在模式$varFindEscaped。如果是,则过滤掉匹配相同模式的那些。否则我们进入下一个文件。

    【讨论】:

    • 嗨,马特,你的代码就像一个魅力!非常感谢!
    猜你喜欢
    • 2021-11-01
    • 1970-01-01
    • 2010-09-15
    • 1970-01-01
    • 1970-01-01
    • 2012-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多