Removing similar lines from two files

对着背影说爱祢 提交于 2019-12-17 20:54:51

问题


I'm trying to find a PowerShell solution to remove lines from file A that are similar in File B. Compare-Object $A $B does the comparing, but how to I go about deleting the items?

File A

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

File B

stackoverflow.com
facebook.com

After Compare: File A

yahoo.com
google.com
twitter.com

回答1:


You can remove the contents of file B from file A with something like this:

$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:


You can try this one line :

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

or using aliases :

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

First you get all the lines, then you group the same ones, you select the unique ones and put into a file.




回答3:


PowerShell and simplicity, walk hand in hand, and I don't see simplicity in these answers. Your initial thought is correct: Compare-Object cmdlet is the way to go.

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

The outcome can piped (or redirected) to a file.



来源:https://stackoverflow.com/questions/31146379/removing-similar-lines-from-two-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!