bash如何比较两个文件

分享于 

4分钟阅读

ubuntu

  繁體

问题

我想逐行比较两个文件,如何才能实现?

File_1.txt:


User1 US


User2 US


User3 US



File_2.txt:


User1 US


User2 US


User3 NG



Output_File:

 
User3 has changed




答案1

查看diff命令,

要执行的命令是diff File_1.txt File_2.txt,它将输出两者之间的差异,并且应该如下所示:

enter image description here

diff ... | tee Output_File 这将把diff的结果管道化到一个|��G��m쌧,然后将输出放入一个文件中,这样,如果你不想立即在控制台上查看所有结果,可以将它保存为以后使用,


答案2

或者你可以使用meld Diff

它提供了文件和目录的双向比较和双向比较,并支持许多流行的版本控制系统。

通过运行以下命令安装:


sudo apt-get install meld



示例:

enter image description here

比较目录:

enter image description here

全文示例:

enter image description here


答案3

你可以用vimdiff

例如:


vimdiff file1 file2




答案4

Meld是一个非常好的工具,但也可以使用diffuse直观地比较两个文件:


diffuse file1.txt file2.txt



enter image description here


答案5

将脚本复制到一个空文件中,将它另存为compare.py,使它可执行,通过命令运行:


/path/to/compare.py <file1> <file2> <outputfile>



脚本:


#!/usr/bin/env python



import sys


file1 = sys.argv[1]; file2 = sys.argv[2]; outfile = sys.argv[3]



def readfile(file):


 with open(file) as compare:


 return [item.replace("n","").split("") for item in compare.readlines()]



data1 = readfile(file1); data2 = readfile(file2)


mismatch = [item[0] for item in data1 if not item in data2]



with open(outfile,"wt") as out:


 for line in mismatch:


 out.write(line+" has changed"+"n")



要打印到文件:


/path/to/compare.py <file1> <file2> <outputfile>



要打印到终端窗口:


/path/to/compare.py <file1> <file2> 



脚本:


#!/usr/bin/env python



import sys



file1 = sys.argv[1]; file2 = sys.argv[2]


try:


 outfile = sys.argv[3]


except IndexError:


 outfile = None



def readfile(file):


 with open(file) as compare:


 return [item.replace("n","").split("") for item in compare.readlines()]



data1 = readfile(file1); data2 = readfile(file2)


mismatch = [item[0] for item in data1 if not item in data2]



if outfile != None:


 with open(outfile,"wt") as out:


 for line in mismatch:


 out.write(line+" has changed"+"n")


else:


 for line in mismatch:


 print line+" has changed"




答案6

可以使用以下命令cmp


cmp -b"File_1.txt""File_2.txt"



输出将为


a b differ: byte 25, line 3 is 125 U 116 N




答案7


diff -y -W 120 File_1.txt File_2.txt



将给出:


User1 US User1 US


User2 US User2 US


User3 US | User3 NG





COM  文件  files  BASH