Compare two text files with duplicates and write the distinct differences to text file

大兔子大兔子 提交于 2020-02-06 10:58:26

问题


I want to compare 2 text files and output the difference in another text file.

compare-object (get-content c:\temp\hostname_old.txt) (get-content c:\temp\hostname_new.txt) | Select-Object -ExpandProperty InputObject | Out-File $Location

hostname_old.txt

server02
server05
server04
server06
server01

hostname_new.txt (has duplicate names)

server04
server01
server02
server04
server02

Result:

server04
server02
server05
server06

Note how server04 and server02 are present in this list of differences, even though they're present in both input files.

This is what I want:

server05
server06

回答1:


Use Select-Object -Unique to eliminate the duplicates before comparing:

compare-object -PassThru `
  (get-content c:\temp\hostname_old.txt) `
  (get-content c:\temp\hostname_new.txt | Select-Object -Unique)

As in this answer to your previous question, -PassThru is used to pass out the differing lines directly, without the [pscustomobject] wrappers (that indicate the source set of the difference via their .SideIndicator property) that Compare-Object outputs by default.



来源:https://stackoverflow.com/questions/54573751/compare-two-text-files-with-duplicates-and-write-the-distinct-differences-to-tex

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