linux下用diff来对比文件差异

全栈 shanhuhai 2975℃

对比文本文件 file1.txt 和 file2.txt 的差异并忽略空白字符

file1.txt:

We become what we think about.
If you cannot do great things, do small things in a great way.
Logic will get you from A to B. Imagination will take you everywhere.
There's a way to do it better – find it.

Life isn’t about getting and having, it’s about giving and being.
I attribute my success to this – I never gave or took any excuse.

file2.txt:

We become what we think about.
If you cannot do great things, do small things in a great way.--Napoleon Hill, Motivational Writer
Logic will get you from A to B. Imagination will take you everywhere.
Life isn’t about getting and having, it’s about giving and being.
What is not started today is never finished tomorrow.
You aspire to do great things? Begin with little ones
I attribute my success to this – I never gave or took any excuse.

执行命令:


diff file1.txt file2.txt -w

这个 -w 参数很有用,比如在 file1.txt 文件中空格是\n 而在 file2.txt 中换行符是 \r\n ,由于各种操作系统使用的换行符不一样,所以这样的情况还是经常见到的,当对比时如果没有 -w 参数,几乎整个文件完全不一样了,那样对比就没意义了,所以每次对比都记得加上 -w

对比结果:

 2c2
 < If you cannot do great things, do small things in a great way.
 ---
 > If you cannot do great things, do small things in a great way.--Napoleon Hill, Motivational Writer
 4,5d3
 < There's a way to do it better – find it.
 < 
 6a5,6
 > What is not started today is never finished tomorrow.
 > You aspire to do great things? Begin with little ones

说明下:
2c2 表示 第二行有改变
< xxx 表示左边的内容
--- 左右两边的分割线
> yyyy 表示右边的内容
接下来
4,5d3 表示左边的4-5行在右边是没有的,或者说被删除了,d(delete),表示删除
接下来
6a5,6 表示右边的5-6行在左边是没有的,或者说是添加的,a(add),表示添加

列模式对比两个文本文件

命令

diff file1.txt file2.txt -w -y -W 50

这样可以更直观的看到两边的不同
| 表示有改变
< 左边有的
> 右边有的

执行下试试

转载请注明:大后端 » linux下用diff来对比文件差异

付费咨询
喜欢 (0)or分享 (0)