【问题标题】:Removing similar lines from two files从两个文件中删除相似的行
【发布时间】:2015-06-30 19:04:42
【问题描述】:

我正在尝试找到一个 PowerShell 解决方案来从文件 A 中删除与文件 B 中相似的行。Compare-Object $A $B 进行比较,但我该如何删除这些项目?

文件 A

yahoo.com
google.com
stackoverflow.com
facebook.com
twitter.com

文件 B

stackoverflow.com
facebook.com

比较后:文件A

yahoo.com
google.com
twitter.com

【问题讨论】:

    标签: powershell text-files string-comparison


    【解决方案1】:

    您可以使用以下方式从文件 A 中删除文件 B 的内容:

    $ref = Get-Content 'C:\path\to\fileB.txt'
    
    (Get-Content 'C:\path\to\fileA.txt') |
      ? { $ref -notcontains $_ } |
      Set-Content 'C:\path\to\fileA.txt'
    

    【讨论】:

      【解决方案2】:

      你可以试试这一行:

      Get-Content 'FileA.txt','FileB.txt' | Group-Object | where-Object {$_.count -eq 1} | Foreach-object {$_.group[0]} | Set-Content 'FileC.txt'
      

      或使用别名:

      gc 'FileA.txt','FileB.txt' | Group | where {$_.count -eq 1} | % {$_.group[0]} | Set-Content 'FileC.txt'
      

      首先获取所有行,然后对相同的行进行分组,然后选择唯一的行并放入文件中。

      【讨论】:

        【解决方案3】:

        PowerShell 和简单性,携手并进,我在这些答案中看不到简单性。您最初的想法是正确的:Compare-Object cmdlet 是要走的路。

        diff $fileA $fileB | ? sideindicator -eq '<=' # v4

        结果可以通过管道传输(或重定向)到文件。

        【讨论】:

        • 您的解决方案不完整。 $fileA$fileB 需要是各自文件的内容,并且(更重要的是)您需要在过滤器之后展开 InputObject 属性以获得所需的输出。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-07
        相关资源
        最近更新 更多