Linux Command - diff

compare the contents from two files

Syntax

1
diff [OPTIONS] file1 file2

Options

Common Option Description
-y --side-by-side Output in two columns.

Example

file1

1
2
3
4
5
6
7
8
line 1
line 2
line 3
line 4
line 5
line x
line y
line z

file2

1
2
3
4
5
6
line 1
line two
line 3
line x
line y
line z

Show Diff

1
diff file1 file2

output

1
2
3
4
5
6
7
8
2c2
< line 2
---
> line two
4,5d3
< line 4
< line 5

Note: there is change in line 2. line 4,5 are deleted

  • c is for change
  • a is for add
  • d is for delete

Diff Side by Side

1
diff -y file1 file2

output

1
2
3
4
5
6
7
8
line 1		line 1
line 2 | line two
line 3 line 3
line 4 <
line 5 <
line x line x
line y line y
line z line z

Note:

  • | means different
  • < means line exist in file1 only
  • means line exist in file2 only

Diff with Context

1
diff -c file1 file2

output

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
*** file1	2019-01-08 23:00:39.033653619 -0500
--- file2 2019-01-08 23:02:27.115428654 -0500
***************
*** 1,8 ****
line 1
! line 2
line 3
- line 4
- line 5
line x
line y
line z
\ No newline at end of file
--- 1,6 ----
line 1
! line two
line 3
line x
line y
line z
\ No newline at end of file

Diff with unified context

1
diff -u file1 file2

output

1
2
3
4
5
6
7
8
9
10
11
12
13
--- file1	2019-01-08 23:00:39.033653619 -0500
+++ file2 2019-01-08 23:02:27.115428654 -0500
@@ -1,8 +1,6 @@
line 1
-line 2
+line two
line 3
-line 4
-line 5
line x
line y
line z
\ No newline at end of file

Generate Patch for a file

1
diff -u file1 file2 > file.patch

file.path content

1
2
3
4
5
6
7
8
9
10
11
12
13
--- file1	2019-01-08 23:00:39.033653619 -0500
+++ file2 2019-01-08 23:02:27.115428654 -0500
@@ -1,8 +1,6 @@
line 1
-line 2
+line two
line 3
-line 4
-line 5
line x
line y
line z
\ No newline at end of file

Apply a patch to a file

1
patch file1.back file.patch

file.patch will apply to file1.back

Reference