Linux 利用 rsync 命令提取增量文件

参考:

rsync 命令:http://man.linuxde.net/rsync

Linux文件夹对比并提取的差分文件技巧-rsync的妙用:https://my.oschina.net/mengshuai/blog/551379


例子:

1. 文件包准备工作

假设我们有一个项目包为 "Test",我们对其copy一份重命名为 "Test.old",再将更新后的项目完整包copy一份命名为 "Test.new":

[[email protected] tar_test]$ ls
Test  Test.new  Test.old
[[email protected] tar_test]$

Test.new 项目包内容为:

[[email protected] tar_test]$ tree Test.new/
Test.new/
|-- dir_test
|   |-- dir_file_new.txt
|   `-- dir_file.txt
|-- empty
|-- empty_new
|-- file-2.txt
|-- file-3.txt
|-- modify_file.txt
`-- new_dir
    `-- test.txt

4 directories, 6 files
[[email protected] tar_test]$

Test.old 项目包内容为:

[[email protected] tar_test]$ tree Test.old/
Test.old/
|-- dir_test
|   |-- dir_file_old.txt
|   `-- dir_file.txt
|-- empty
|-- empty_old
|-- file-1.txt
|-- file-2.txt
`-- modify_file.txt

3 directories, 5 files
[[email protected] tar_test]$ 

Test.old包 与 Test.new 包对比结果为:

[[email protected] tar_test]$ diff -rs Test.new/ Test.old/
Only in Test.new/dir_test: dir_file_new.txt
Only in Test.old/dir_test: dir_file_old.txt
Files Test.new/dir_test/dir_file.txt and Test.old/dir_test/dir_file.txt are identical
Only in Test.new/: empty_new
Only in Test.old/: empty_old
Only in Test.old/: file-1.txt
Files Test.new/file-2.txt and Test.old/file-2.txt are identical
Only in Test.new/: file-3.txt
diff -rs Test.new/modify_file.txt Test.old/modify_file.txt
1c1
< modify content test: after
---
> modify content test: befor
Only in Test.new/: new_dir
[[email protected] tar_test]$

2.获取差异文件列表

以 Test.new 包为基准,利用 rsync 命令获取增量文件列表:

[[email protected] tar_test]$ rsync -rcnC --out-format="%n" Test.new/ Test.old/                                 
file-3.txt
modify_file.txt
dir_test/dir_file_new.txt
empty_new/
new_dir/
new_dir/test.txt
[[email protected] tar_test]$

可以看到,这里默认会显示出文件夹,所以要过滤掉以『/』结尾的文件夹的显示:

[[email protected] tar_test]$ rsync -rcnC --out-format="%n" Test.new/ Test.old/ |grep -v "/$"
file-3.txt
modify_file.txt
dir_test/dir_file_new.txt
new_dir/test.txt
[[email protected] tar_test]$

有了增量文件列表,复制的操作方法就很多了。

3.复制差异文件到新目录

可以继续使用 rsync 同步到新的 out 目录,以防止多次执行后错误文件修复问题:

[[email protected] tar_test]$ rsync -rcnC --out-format="%n" Test.new/ Test.old/ |grep -v "/$" |xargs -I{} rsync -R Test/{} out/
[[email protected] tar_test]$ tree out/
out/
`-- Test
    |-- dir_test
    |   `-- dir_file_new.txt
    |-- file-3.txt
    |-- modify_file.txt
    `-- new_dir
        `-- test.txt

3 directories, 4 files
[[email protected] tar_test]$
最后,out 文件夹下的 Test 包即可作为本次项目修改的增量包。


你可能感兴趣的:(学习笔记)