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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18065827/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 06:08:18  来源:igfitidea点击:

Copy differences between two files in unix

linuxbashunix

提问by Steam

Firstly, which is the best and fastest unix command to get only the differences between two files ? I tried using diff to do it (below).

首先,哪个是仅获取两个文件之间差异的最佳和最快的 unix 命令?我尝试使用 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:)"

输出 - “#这里有很多空格#>很高兴来到这里:)”

Expected output -Glad to be here:)

预期输出 -很高兴来到这里:)

回答by anubhava

Another way to get diff is by using awk:

另一种获取差异的方法是使用 awk:

awk 'FNR==NR{a[
+Glad to be here:)
];next}!(
diff -a --suppress-common-lines -y file1.txt file2.txt|tr 'a >' '' |awk '{print }' >>file3.txt 
in a)' file1 file2

Though I must admit that I haven't run any benchmarks and can't say which is the fastest solution.

虽然我必须承认我没有运行任何基准测试,也不能说哪个是最快的解决方案。

回答by Spencer Rathbun

The -yoption to diff makes it produce a "side by side" diff, which is why you have the spaces. Try -u 0for the unified format with zero lines of context. That should print:

-y选项差异使得它产生差异,这就是为什么你有空间“肩并肩”。尝试-u 0使用零行上下文的统一格式。那应该打印:

##代码##

The plus means the line was added, whereas a minus means it was removed.

加号表示添加了该行,而减号表示已删除该行。

回答by Nagarjun Reddy Manne

##代码##