问题
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