Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux技術

find 指令的 -exec 參數用法

find 的 -exec 可在搜尋完成後,對符合條件的檔案執行其他指令。基本格式為:

find [路徑] [條件] -exec [指令] {} \;

{} 代表 find 找到的檔案,分號是 -exec 的結束符號,因此前面需加反斜線。

常見範例

列出所有檔案詳細資訊:

find . -type f -exec ls -l {} \;

刪除十天前修改的檔案並提示確認:

find . -type f -mtime +10 -exec rm -i {} \;

使用 -ok 也能在刪除前互動確認:

find . -type f -mtime +10 -ok rm {} \;

在 passwd 檔案中搜尋 root:

find /etc -name "passwd*" -exec grep "root" {} \;

將符合 mv* 的檔案移到 newDir:

find . -name "mv*" -exec mv {} newDir \;

合併多個檔案內容:

find . -name "t*.txt" -mtime -1 -exec cat {} \; > ./Document/all.txt

以 printf 格式化輸出:

find ./Documents -type f -name "*.txt" -exec printf "File: %s\n" {} \;

補充

exec 與 fork 概念不同。exec 會以新進程內容取代原進程,PID 不變;fork 則建立子進程。find -exec 會為每個符合檔案啟動指令,因此大量檔案時需注意效能。

Copyright © Linux教程網 All Rights Reserved