compare two files in UNIX

前端 未结 4 960
南笙
南笙 2020-12-13 10:21

I would like to compare two files [ unsorted ] file1 and file2. I would like to do file2 - file1 [ the difference ] irrespective of the line number? diff is not working.

相关标签:
4条回答
  • 2020-12-13 10:55

    There are 3 basic commands to compare files in unix:

    1. cmp : This command is used to compare two files byte by byte and as any mismatch occurs,it echoes it on the screen.if no mismatch occurs i gives no response. syntax:$cmp file1 file2.

    2. comm : This command is used to find out the records available in one but not in another

    3. diff

    0 讨论(0)
  • 2020-12-13 11:04

    I got the solution by using comm

    comm -23 file1 file2 
    

    will give you the desired output.

    The files need to be sorted first anyway.

    0 讨论(0)
  • 2020-12-13 11:14

    Well, you can just sort the files first, and diff the sorted files.

    sort file1 > file1.sorted
    sort file2 > file2.sorted
    diff file1.sorted file2.sorted
    

    You can also filter the output to report lines in file2 which are absent from file1:

    diff -u file1.sorted file2.sorted | grep "^+" 
    

    As indicated in comments, you in fact do not need to sort the files. Instead, you can use a process substitution and say:

    diff <(sort file1) <(sort file2)
    
    0 讨论(0)
  • 2020-12-13 11:18

    Most easy way: sort files with sort(1) and then use diff(1).

    0 讨论(0)
提交回复
热议问题