由 find 引伸出的盲区

 以前对于 find 的水平仅仅停留在查找某个文件路径方面,看到别人在后面加 "-exec ... {} \; "感受特别高大上,今天抽空细细回味了一番。html

 

“你之因此看不到黑暗,是由于有人把它挡在你看不到的地方”。linux

“历来就没有什么岁月静好,只是有人替咱们负重前行”。shell

Linux find 命令用来在指定目录下查找文件。任何位于参数以前的字符串都将被视为欲查找的目录名。express

若是使用该命令时,不设置任何参数,则find命令将在当前目录下查找子目录与文件。而且将查找到的子目录和文件所有进行显示。安全

其语法格式以下:bash

find   path   -option   [   -print ]   [ -exec   -ok   command ]   {} \;

我在 /opt 目录下建立了 1.txt,在 /root 目录下分别建立了 1.log、2.log、3.log,并追加了少许内容。spa

 

如下咱们使用 exec 和 xargs 查找一些东西进行对比:.net

若是咱们想要查找在 50 分钟内被修改(更新)过的文件能够表示以下code

[root@reset ~]# find . -type f -cmin -50 -exec ls -l {} \;
-rw-r--r-- 1 root root 30 Dec  6 14:42 ./1.log
-rw-r--r-- 1 root root 28 Dec  6 14:43 ./3.log
-rw-r--r-- 1 root root 26 Dec  6 14:43 ./2.log

[root@reset ~]# find . -type f -cmin -50 |xargs ls -l
total 32
-rw-r--r-- 1 root root   30 Dec  6 14:42 1.log
-rw-r--r-- 1 root root   26 Dec  6 14:43 2.log
-rw-r--r-- 1 root root   28 Dec  6 14:43 3.log
drw-r-x--- 2 root root 4096 Dec  6 13:40 config
-rw-r----- 1 root root   55 Dec  5 14:38 master.dat
-rw-r----- 1 root root   32 Dec  5 14:39 test.dat
-rw-r----- 1 root root  127 Dec  5 15:15 w.sh
drw-r-x--- 2 root root 4096 Oct 23 16:37 zhouyuyao

查找指定目录下 30 分钟内被修改(更新)过的文件并查看文件大小能够表示以下htm

[root@reset ~]# find /opt/ -type f -cmin -30 -exec du -sh {} \;
4.0K    /opt/1.txt

[root@reset ~]# find /opt/ -type f -cmin -30 |xargs du -sh
4.0K    /opt/1.txt

固然也能够查看一天内修改(更新)过的文件

[root@reset ~]# find /opt/  -type f -ctime -1 -exec ls -l {} \;
-rw-r--r-- 1 root root 1413 Dec  6 15:58 /opt/1.txt

[root@reset ~]# find /opt/  -type f -ctime -1 |xargs ls -l
-rw-r--r-- 1 root root 1413 Dec  6 15:58 /opt/1.txt

以及一天前修改(更新)过的文件

[root@reset ~]# find /opt/ -type f -ctime +1 -exec ls -l {} \;
-rw-r--r-- 1 root root 37 Nov 25 16:25 /opt/jenkins/index.html

[root@reset ~]# find /opt/ -type f -ctime +1 |xargs ls -l
-rw-r--r-- 1 root root 37 Nov 25 16:25 /opt/jenkins/index.html

 

区别描述: 二者都是对符合条件的文件执行所给的 Linux 命令,而不询问用户是否须要执行该命令。

-exec:{} 表示命令的参数即为所找到的文件,以;表示 command 命令的结束。\ 是转义符,
由于分号在命令中还有它用途,因此就用一个 \ 来限定表示这是一个分号而不是表示其它意思。

-ok: 和 -exec 的做用相同,格式也同样,只不过以一种更为安全的模式来执行该参数
所给出的 shell 给出的这个命令以前,都会给出提示,让用户来肯定是否执行。

xargs 要结合管道来完成

find [option] express |xargs command

 

相比之下,也不难看出各自的缺点
一、exec 每处理一个文件或者目录,它都须要启动一次命令,效率很差; 
二、exec 格式麻烦,必须用 {} 作文件的代位符,必须用 \; 做为命令的结束符,书写不便。
三、xargs 不能操做文件名有空格的文件;

综上,若是要使用的命令支持一次处理多个文件,而且也知道这些文件里没有带空格的文件,
那么使用 xargs 比较方便; 不然,就要用 exec 了。

 

 

 

 

参考资料

1. exec与xargs区别

2. Linux xargs 命令

3. Linux find命令

4. linux 中强大且经常使用命令:find、grep

5. linux xargs命令的使用及其与exec、管道的区别

相关文章
相关标签/搜索