在 Bash 中,可以使用 rsync
命令有选择地将目录从一个树复制到另一个树。rsync
是一个强大的文件传输工具,它允许你根据特定的规则来同步文件和目录。
rsync
命令通过比较源目录和目标目录的内容,只传输发生变化的部分,从而提高传输效率。它支持本地文件系统之间的复制,也支持通过网络进行远程复制。
假设你想将 /source/tree
目录中的所有 .txt
文件复制到 /destination/tree
,并且只复制修改过的文件,可以使用以下命令:
rsync -avz --include='*.txt' --exclude='*' /source/tree/ /destination/tree/
解释:
-a
:归档模式,表示递归同步并且保持文件的所有属性。-v
:详细模式,显示同步过程中的详细信息。-z
:压缩文件数据,在传输过程中进行压缩以提高传输速度。--include='*.txt'
:包含所有 .txt
文件。--exclude='*'
:排除其他所有文件。如果你在复制过程中遇到权限不足的问题,可以尝试使用 sudo
提升权限:
sudo rsync -avz --include='*.txt' --exclude='*' /source/tree/ /destination/tree/
如果你需要复制符号链接,可以使用 -l
选项:
rsync -avzl --include='*.txt' --exclude='*' /source/tree/ /destination/tree/
如果你需要排除某个特定的子目录,可以使用 --exclude
选项:
rsync -avz --include='*.txt' --exclude='/source/tree/exclude_dir/*' /source/tree/ /destination/tree/
通过这些方法,你可以灵活地控制 rsync
命令的行为,以满足不同的复制需求。
领取专属 10元无门槛券
手把手带您无忧上云