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两个文件了。归档也是同样的道理,如果遇到这种有空格的文件名,就会被归档成连个文件,破坏了归档后文件的一致性。

猜你喜欢

转载自www.cnblogs.com/anttech/p/11291590.html