【问题标题】:Loop through file and remove several lines with different text遍历文件并删除具有不同文本的几行
【发布时间】:2015-02-18 15:27:24
【问题描述】:

我正在尝试遍历文件并删除不需要的行。文件中的行具有不变的唯一编号。到目前为止,我所拥有的并没有删除 foreach 循环中的行,而是单独删除了。

$FSEFiles=get-childitem E:\FSE*.txt

foreach ($file in $FSEFiles)

{

    try

    {
        (Get-Content $file.PSPath) | 
        Foreach-Object  { Where-Object { $_ -notmatch "15987@" } } |
        Foreach-Object  { Where-Object { $_ -notmatch "16422@" } } | 
        #Foreach-Object {Where-Object { $_ -notmatch "17526@"}} | 
        #Foreach-Object {Where-Object { $_ -notmatch "17527@"}} | 
        #Foreach-Object {Where-Object { $_ -notmatch "17528@"}} | 
        #Foreach-Object {Where-Object { $_ -notmatch "17530@"}} | 
        #Foreach-Object {Where-Object { $_ -notmatch "17531@"}} | 
        #Foreach-Object {Where-Object { $_ -notmatch "17532@"}} | 
        Set-Content $file.PSPath

        write-host $file updated
    }
    catch
    {
        write-host Error editing $file
    }
}

我是否遗漏了一些可以让这个循环在每一行上工作的东西?

【问题讨论】:

    标签: loops powershell foreach where


    【解决方案1】:

    既然您已经在使用正则表达式,那么让我们将所有这些要求合并到一个漂亮的正则表达式字符串中

    $regex = "(15987@|16422@|1752[6-8]@|1753[0-2]@)"
    
    $data = Get-Content $file.PSPath 
    $data | Where-Object{$_ -notmatch $regex} | Set-Content $file.PSPath
    

    也许类似的东西会简化它。没有真正经过测试,但应该可以工作。您可能已经完成了工作,但是 foreachwhere 的组合似乎格式不正确(因此是问题),但尝试解决我认为的问题是多余的。

    【讨论】:

    • 完美!这正是我需要它做的。谢谢。
    • 很高兴有帮助。请考虑在左侧投票下用复选标记将此标记为答案。
    猜你喜欢
    • 2018-03-16
    • 2018-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-18
    • 1970-01-01
    • 2021-12-28
    • 2019-01-24
    相关资源
    最近更新 更多