以前對於 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區別
3. Linux find命令