从两个文件中删除相似的行

Removing similar lines from two files

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

文件A

yahoo.com
google.com
whosebug.com
facebook.com
twitter.com

文件 B

whosebug.com
facebook.com

比较后: 文件 A

yahoo.com
google.com
twitter.com

您可以使用如下方式从文件 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'

你可以试试这一行:

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'

首先你得到所有的行,然后你将相同的行分组,你 select 独特的行并放入文件中。

PowerShell 和简单性并驾齐驱,我在这些答案中看不到简单性。您最初的想法是正确的:Compare-Object cmdlet 是正确的选择。

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

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