用 diff -u 生成补丁并用 patch 应用

生成两个文件的统一格式差异(unified diff),用 patch 应用到另一份拷贝,用 patch -R 反向撤销。

Linuxdiff 文件对比补丁文本低风险
运行 `diff -u 旧文件 新文件 > fix.patch` 生成补丁,再 `patch 文件 < fix.patch` 应用(`patch -R` 撤销)。

01命令

命令
$ diff -u original.txt new.txt > changes.patch && patch original.txt < changes.patch

02作用说明

不加 -u 得到的是简略的普通差异格式;统一格式带有上下文行,即使行号有偏移 patch 也能定位修改点。应用前可以用 `patch --dry-run < fix.patch` 安全预览;对整个目录树,标准做法是 `diff -ruN 旧目录 新目录` 生成补丁、用 `patch -p1` 应用。另外 diff 的退出码有讲究:内容不同返回 1,相同返回 0,写 shell 脚本时很有用。

03风险

风险低风险
使用条件diffutils and patch (patch may need installing: apt install patch)
!注意: patch 会直接修改文件,应用前保留备份或用 --dry-run 预览。

04撤销

撤销
$ patch -R original.txt < changes.patch

05来源

  • patch(1) - Linux manual page
    Ubuntu Manpages · technical · 2026-09-17
    依据: patch applies a diff to a file, with -R to reverse the patch and --dry-run to preview the result without modifying files.
  • diff(1) - Linux manual page
    Ubuntu Manpages · technical · 2026-09-17
    依据: diff -u outputs the differences in unified context format suitable for consumption by the patch program.

最后验证: 2026-09-17 · 分类: 文件与文件夹