find命令的高级用法之print0及depth
从一条命令开始:
find ~ -depth -print0 |cpio --null -ov -F /tmp/tree1.cpio
(1)find ~ -depth
find ~ -depth是什么意思?
[root@localhost test]# man find -depth Process each directory's contents before the directory itself. The -delete action also implies -depth.
在处理目录以前首先处理目录下的子内容。
也就是说在不加-depth的时候, 处理顺序是首先处理目录本身,然后处理目录下的子内容。加不加-depth参数,会影响输出结构的输出顺序。
其实只是查询出来的顺序不同。
[root@localhost ~]# mkdir -p test/test1/test2/test3 [root@localhost ~]# find test -depth test/test1/test2/test3 test/test1/test2 test/test1 test
[root@localhost ~]# find test
test
test/test1
test/test1/test2
test/test1/test2/test3
所以说我们在归档家目录下的文件的时候,使用 find ~ -depth 表示归档先从子目录下开始查找归档,直到最上层目录。
拓展:
除了depth以外还有maxdepth和mindepth
[root@localhost ~]# find test -depth test/test1/test2/test3 test/test1/test2 test/test1 test [root@localhost ~]# find test -maxdepth 2 test test/test1 test/test1/test2 [root@localhost ~]# find test -mindepth 2 test/test1/test2 test/test1/test2/test3
由此可见maxdepth mun(数字)表示最多查找多少层目录,mindepth num(数字)表示最少查找多少层目录;我们说,查找一个文件,为了节省查找时间,我们可以设置这样的查找目录的深度。
(2)find ~ -depth -print0
-print0是什么意思?
[root@localhost ~]# find test -depth test/test1/test2/test3 test/test1/test2 test/test1 test [root@localhost ~]# find test -depth -print0 test/test1/test2/test3test/test1/test2test/test1test[root@localhost ~]#
我们可以看出,使用-print0将会把查找的内容以一个整行的形式呈现数来,为什么需要这样来做呢?
在默认的情况下,find的默认在每一个结果后面加一个“\n”(换行),所以输出的结果是一行一行的,但是如果文件名中有空格或者换行符号,find输出的内容将会是两行,影响归档的准确性。为了避免这种情况的发生,我们需要使用 -print0参数,然后在结合cpio的解析空字符“--null”参数,保证归档数据的一致性。
例如: 我们创建一个文件“file 1.txt”,这是一个文件,文件名有空格 [root@localhost test]# touch "file 1.txt" [root@localhost test]# ls file 1.txt test1 用find查找这个文件并删除 [root@localhost test]# find . -depth -name file* |xargs rm rm: 无法删除"./file": 没有那个文件或目录 rm: 无法删除"1.txt": 没有那个文件或目录
我发发现,“file 1.txt”文件被识别成了file和1.txt两个文件了。归档也是同样的道理,如果遇到这种有空格的文件名,就会被归档成连个文件,破坏了归档后文件的一致性。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现