简体   繁体   English

复制unix中两个文件之间的差异

[英]Copy differences between two files in unix

Firstly, which is the best and fastest unix command to get only the differences between two files ? 首先,哪个是最好和最快的unix命令才能获得两个文件之间的差异? I tried using diff to do it (below). 我尝试使用diff来做(下图)。

I tried the answer given by Neilvert Noval over here - Compare two files line by line and generate the difference in another file 我尝试了Neilvert Noval在这里给出的答案 - 逐行比较两个文件并在另一个文件中生成差异

code - 代码 -

diff -a --suppress-common-lines -y file1.txt file2.txt >> file3.txt

But, I get a lot of spaces and a > symbol also before the different lines. 但是,我在不同的行之前也得到了很多空格和一个>符号。 How do I fix that ? 我该如何解决这个问题? I was thinking of removing trailing spaces and the first '>', but not sure if that is a neat fix. 我想删除尾随空格和第一个'>',但不确定这是否是一个整洁的修复。

My file1.txt has - 我的file1.txt有 -

Hello World!
Its such a nice day!
#this is a newline and not a line of text# 

My file1.txt has - 我的file1.txt有 -

Hello World!
Its such a nice day!
Glad to be here!
#this is a newline and not a line of text# 

Output - " #Many spaces here# > Glad to be here:)" 输出 - “#Many space here#>很高兴来到这里:)”

Expected output - Glad to be here:) 预期产量 -很高兴来到这里:)

Another way to get diff is by using awk: 另一种获得差异的方法是使用awk:

awk 'FNR==NR{a[$0];next}!($0 in a)' file1 file2

Though I must admit that I haven't run any benchmarks and can't say which is the fastest solution. 虽然我必须承认我没有运行任何基准测试,但不能说哪个是最快的解决方案。

The -y option to diff makes it produce a "side by side" diff, which is why you have the spaces. diff的-y选项使它产生“并排”差异,这就是为什么你有空格。 Try -u 0 for the unified format with zero lines of context. 尝试-u 0表示统一格式,零行上下文。 That should print: 那应该打印:

+Glad to be here:)

The plus means the line was added, whereas a minus means it was removed. 加号表示添加了行,而减号表示删除了行。

diff -a --suppress-common-lines -y file1.txt file2.txt|tr 'a >' '' |awk '{print $1}' >>file3.txt 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM